Dynamic Class Property $$Value in PHP

dynamic class property $$value in php

You only need to use one $ when referencing an object's member variable using a string variable.

echo $this->$string;

Getting a value of a dynamic class and dynamic property

eval does not return result of evaluated, if you want to store property value in $val, you have to include it in evaluated string:

$a = 'user->prop';
$eval = '$val = $'.$a.';';

eval($eval);
var_dump($val);

How do I dynamically write a PHP object property name?

Update for PHP 7.0

PHP 7 introduced changes to how indirect variables and properties are handled at the parser level (see the corresponding RFC for more details). This brings actual behavior closer to expected, and means that in this case $obj->$field[0] will produce the expected result.

In cases where the (now improved) default behavior is undesired, curly braces can still be used to override it as shown below.

Original answer

Write the access like this:

$obj->{$field}[0]

This "enclose with braces" trick is useful in PHP whenever there is ambiguity due to variable variables.

Consider the initial code $obj->$field[0] -- does this mean "access the property whose name is given in $field[0]", or "access the element with key 0 of the property whose name is given in $field"? The braces allow you to be explicit.

Is it possible to define a class property value dynamically in PHP?

You can put it into the constructor like this:

public function __construct() {
$this->fullname = $this->firstname.' '.$this->lastname;
$this->totalBal = $this->balance+$this->newCredit;
}

Why can't you do it the way you wanted? A quote from the manual explains it:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

For more infromation about OOP properties see the manual: http://php.net/manual/en/language.oop5.properties.php

Undefined property in dynamic variable of a PHP class

Since you're using variable variables, put them in quotes, then concatenate:

echo $this->{'date_' . $this->type};
// not $type, use `$this->` since it's part of your properties

Or using via formatted string (double quotes will work as well):

echo $this->{"date_{$this->type}"};

Getting static property from a class with dynamic class name in PHP

If you are using PHP 5.3.0 or greater, you can use the following:

$classname::$$propertyname;


Unfortunately, if you are using a version lower than 5.3.0, you are stuck using eval() (get_class_vars() will not work if the value is dynamic).

$value = eval($classname.'::$'.$propertyname.';');


EDIT: I've just said get_class_vars() wouldn't work if the value is dynamic, but apparently, variable static members are part of "the default properties of a class". You could use the following wrapper:

function get_user_prop($className, $property) {
if(!class_exists($className)) return null;
if(!property_exists($className, $property)) return null;

$vars = get_class_vars($className);
return $vars[$property];
}

class Foo { static $bar = 'Fizz'; }

echo get_user_prop('Foo', 'bar'); // echoes Fizz
Foo::$bar = 'Buzz';
echo get_user_prop('Foo', 'bar'); // echoes Buzz

Unfortunately, if you want to set the value of the variable, you will still need to use eval(), but with some validation in place, it's not so evil.

function set_user_prop($className, $property,$value) {
if(!class_exists($className)) return false;
if(!property_exists($className, $property)) return false;

/* Since I cannot trust the value of $value
* I am putting it in single quotes (I don't
* want its value to be evaled. Now it will
* just be parsed as a variable reference).
*/
eval($className.'::$'.$property.'=$value;');
return true;
}

class Foo { static $bar = 'Fizz'; }

echo get_user_prop('Foo', 'bar'); // echoes Fizz
set_user_prop('Foo', 'bar', 'Buzz');
echo get_user_prop('Foo', 'bar'); // echoes Buzz

set_user_prop() with this validation should be secure. If people start putting random things as $className and $property, it will exit out of the function as it won't be an existing class or property. As of $value, it is never actually parsed as code so whatever they put in there won't affect the script.

How to dynamically assign a value to a class property in PHP?

$obj->$propName = $value;

PHP Access static property from dynamic class name

I solved it.

The static variable can be accessed by:

public function getMyVar($classname) {
return $classname::$myvar;
}

That was a lot easier than anticipated! :)

How to set class variables dynamically?

So, you want to dynamically call setters?

$y = new stdClass();
$y->prop1 = "something";

$targetProperty = "prop1";
$y->$targetProperty = "something else";
echo $y->prop1;

//Echos "something else"

That what you're looking for?

How to declare dynamic PHP class with {'property-names-like-this'}

I used code like this:

class myClass
{

function __construct() {

// i had to initialize class with some default values
$this->{'fvalue-string'} = '';
$this->{'fvalue-int'} = 0;
$this->{'fvalue-float'} = 0;
$this->{'fvalue-image'} = 0;
$this->{'fvalue-datetime'} = 0;
}
}


Related Topics



Leave a reply



Submit