- Can You Create Instance Properties Dynamically in PHP
- Can you create instance properties dynamically in PHP?
- How to create new property dynamically
- PHP set object properties dynamically
- Dynamically creating instance variables in PHP classes
- How do you access a dynamic property in an object?
- How do I dynamically write a PHP object property name?
- Update for PHP 7.0
- Original answer
- Dynamically Create Instance Method in PHP
- Dynamically create PHP object based on string
- dynamic class property $$value in php
- PHP Class properties
- property declaration and access
- Example
- Output
- Example
- How do I create a PHP static class property at runtime (dynamically)?
- I want a dictionary of properties inside my class.
- I want to associate some values to a class, or: I want a dictionary of properties inside some one else’s class.
- I want to change, not create, an existing property of a class.
Can You Create Instance Properties Dynamically in PHP
Can you create instance properties dynamically in PHP?
Sort of. There are magic methods that allow you to hook your own code up to implement class behavior at runtime:
class foo public function __get($name) return('dynamic!');
>
public function __set($name, $value) $this->internalData[$name] = $value;
>
>
That’s an example for dynamic getter and setter methods, it allows you to execute behavior whenever an object property is accessed. For example
would print, in this case, «dynamic!» and you could also assign a value to an arbitrarily named property in which case the __set() method is silently invoked. The __call($name, $params) method does the same for object method calls. Very useful in special cases. But most of the time, you’ll get by with:
class foo public function __construct() foreach(getSomeDataArray() as $k => $value)
$this-> = $value;
>
>
. because mostly, all you need is to dump the content of an array into correspondingly named class fields once, or at least at very explicit points in the execution path. So, unless you really need dynamic behavior, use that last example to fill your objects with data.
This is called overloading
http://php.net/manual/en/language.oop5.overloading.php
How to create new property dynamically
There are two methods to doing it.
One, you can directly create property dynamically from outside the class:
class Foo
>
$foo = new Foo();
$foo->hello = 'Something';
Or if you wish to create property through your createProperty method:
class Foo public function createProperty($name, $value) $this-> = $value;
>
>
$foo = new Foo();
$foo->createProperty('hello', 'something');
PHP set object properties dynamically
You can using Reflection , I think.
function set(array $array) $refl = new ReflectionClass($this);
foreach ($array as $propertyToSet => $value) $property = $refl->getProperty($propertyToSet);
if ($property instanceof ReflectionProperty) $property->setValue($this, $value);
>
>
>
$a = new A();
$a->set(
array(
'a' => 'foo',
'b' => 'bar'
)
);
var_dump($a);
object(A)[1]
public 'a' => string 'foo' (length=3)
public 'b' => string 'bar' (length=3)
Dynamically creating instance variables in PHP classes
Yes that will indeed work. Auto-created instance variables are given public visibility.
How do you access a dynamic property in an object?
$var = json_decode(json_encode(array('1' => 'Object one','2' => 'Object two')));
$num = "2";
var_dump( $var->$num );
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:
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.
Dynamically Create Instance Method in PHP
You are assigning the anonymous function to a property, but then try to call a method with the property name. PHP cannot automatically dereference the anonymous function from the property. The following will work
class Foo
function __construct() $this->sayHi = create_function( '', 'print "hi";');
>
>
$foo = new Foo;
$fn = $foo->sayHi;
$fn(); // hi
You can utilize the magic __call method to intercept invalid method calls to see if there is a property holding a callback/anonymous function though:
class Foo
public function __construct()
$this->sayHi = create_function( '', 'print "hi";');
>
public function __call($method, $args)
if(property_exists($this, $method)) if(is_callable($this->$method)) return call_user_func_array($this->$method, $args);
>
>
>
>
$foo = new Foo;
$foo->sayHi(); // hi
As of PHP5.3, you can also create Lambdas with
See the PHP manual on Anonymous functions for further reference.
Dynamically create PHP object based on string
But know of no way to dynamically create a type based on a string. How does one do this?
You can do it quite easily and naturally:
$type = 'myclass';
$instance = new $type;
If your query is returning an associative array, you can assign properties using similar syntax:
// build object
$type = $row['type'];
$instance = new $type;
// remove 'type' so we don't set $instance->type = 'foo' or 'bar'
unset($row['type']);
// assign properties
foreach ($row as $property => $value) $instance->$property = $value;
>
dynamic class property $$value in php
You only need to use one $ when referencing an object’s member variable using a string variable.
PHP Class properties
Data members declared inside class are called properties. Property is sometimes referred to as attribute or field. In PHP, a property is qualified by one of the access specifier keywords, public, private or protected. Name of property could be any valid label in PHP. Value of property can be different for each instance of class. That’s why it is sometimes referred as instance variable.
Inside any instance method, property can be accessed by calling object’s context available as a pesudo-variable $this. If a property is declared as public, it is available to object with the help of -> operator. If a property is defined with static keyword, its value is shared among all objects of the class and is accessed using scope resolution operator (::) and name of class.
property declaration and access
This example shows how a property is defined and accessed
Example
fname
"; echo "$this->mname
"; echo myclass::$lname; > > $obj=new myclass(); $obj->dispdata(); ?>
Output
The output of above code is as follows −
Outside class, instance properties declared as public are available to object, but private properties are not accessible. In previous versions of PHP, var keyword was available for property declaration. Though it has now been deprecated, it is still available for backward compatibility and is treated as public declaration of property.
PHP 7.4 introduces type declaration of property variables
Example
name=$x; $this->age=$y; > > $obj=new myclass("Kiran",20); ?>
How do I create a PHP static class property at runtime (dynamically)?
I don’t know exactly why you would want to do this, but this works. You have to access the dynamic ‘variables’ like a function because there is no __getStatic() magic method in PHP yet.
class myclass < static $myvariablearray = array(); public static function createDynamic($variable, $value)< self::$myvariablearray[$variable] = $value; >public static function __callstatic($name, $arguments) < return self::$myvariablearray[$name]; >> myclass::createDynamic('module', 'test'); echo myclass::module();
static variables must be part of the class definition, so you can’t create them dynamically. Not even with Reflection:
chuck at manchuck dot com 2 years ago
It is important to note that calling ReflectionClass::setStaticPropertyValue will not allow you to add new static properties to a class.
But this looks very much like a XY Problem. You probably don’t really want to add static properties to a PHP class at runtime; you have some use case that could be fulfilled also that way. Or that way would be the fastest way, were it available, to fulfill some use case. There well might be other ways.
Actually the use cases below are yet again possible solutions to some higher level problem. It might be worth it to reexamine the high level problem and refactor/rethink it in different terms, maybe skipping the need of meddling with static properties altogether.
I want a dictionary of properties inside my class.
trait HasDictionary < private static $keyValueDictionary = [ ]; public static function propget($name) < if (!array_key_exists($name, static::$keyValueDictionary) < return null; >return static::$keyValueDictionary[$name]; > public static function propset($name, $value) < if (array_key_exists($name, static::$keyValueDictionary) < $prev = static::$keyValueDictionary[$name]; >else < $prev = null; >static::$keyValueDictionary[$name] = $value; return $prev; > > class MyClass
I want to associate some values to a class, or: I want a dictionary of properties inside some one else’s class.
This actually happened to me and I found this question while investigating ways of doing it. I needed to see, in point B of my workflow, in which point («A») a given class had been defined, and by what other part of code. In the end I stored that information into an array fed by my autoloader, and ended up being able to also store the debug_backtrace() at the moment of class first loading.
// Solution: store values somewhere else that you control. class ClassPropertySingletonMap < use Traits\HasDictionary; // same as before public static function setClassProp($className, $prop, $value) < return self::propset("::", $value); > public static function getClassProp($className, $prop) < return self::propget("::"); > > // Instead of // $a = SomeClass::$someName; // SomeClass::$someName = $b; // we'll use // $a = ClassPropertySingletonMap::getClassProp('SomeClass','someName'); // ClassPropertySingletonMap::setClassProp('SomeClass','someName', $b);
I want to change, not create, an existing property of a class.
// Use Reflection. The property is assumed private, for were it public // you could do it as Class::$property = $whatever; function setPrivateStaticProperty($class, $property, $value) < $reflector = new \ReflectionClass($class); $reflector->getProperty($property)->setAccessible(true); $reflector->setStaticPropertyValue($property, $value); $reflector->getProperty($property)->setAccessible(false); >