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:For more infromation about OOP properties see the manual: http://php.net/manual/en/language.oop5.properties.phpThis 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.
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
How to Check Is Timezone Identifier Valid from Code
Make Woocommerce Checkout Phone Field Optional Based on Shipping Country
Symfony 2.7 Cache:Clear Command Checks Every Database Connection
Function to Add Dashes to Us Phone Number in PHP
How to Add 5 Minutes to Current Datetime on PHP < 5.3
Pdo_Sqlite Driver Not Present.. What to Do
PHP MySQL Charset Utf8 Problems
Xpath Get Attribute Value in PHP
Laravel 4 - Including a "Partial" View Within a View (Without Using Blade Template)
PHP Search Array Key and Get Value
Cannot Set Date.Timezone in PHP.Ini File
Extend Request Class in Laravel 5
PHP Dynamically Create CSV: Skip the First Line of a CSV File
When Should I Close a Database Connection in PHP
Where to Store Database Login Credentials for a PHP Application