Set property by name php

PHP 8.2: Dynamic Properties are deprecated

In PHP classes, it is possible to dynamically set and retrieve class properties that are not declared. These properties do not adhere to a specific (similar to typed properties), and it requires the use of __get() and __set() magic methods to effectively prevent or control how dynamic properties are set and retrieved.

class User < private int $uid; >$user = new User(); $user->name = 'Foo';

In the snippet above, the User class does not declare a property with name name , but because dynamic properties are allowed, PHP allows setting it.

While dynamic properties provide the flexibility in creating classes such as value objects without a strict class declaration, it opens the possibility of potential bugs and unexpected behaviors in applications . For example, a typo in a statement that sets a property could go unnoticed because PHP silently allows all dynamic properties.

In PHP 8.2 and later, setting a value to an undeclared class property is deprecated, and emits a deprecation notice the first time the property is set during the lifetime of the application execution.

class User < private int $uid; >$user = new User(); $user->name = 'Foo';
Deprecated: Creation of dynamic property User::$name is deprecated in . on line . 

Setting the properties from within the class also emits the deprecation notice:

class User < public function __construct() < $this->name = 'test'; > > new User();
Deprecated: Creation of dynamic property User::$name is deprecated in . on line . 

There are legitimate use cases of dynamic properties, such as value objects derived from a dynamic JSON response, or configuration objects that allow arbitrary values.

Читайте также:  Decimal sql to java

Ideally, classes should declare the dynamic properties in the class to avoid the deprecation notice. It is not required to declare the property with a property type.

Exempted Dynamic Property Patterns

There are three exceptions to this deprecation. Utilizing one of the approaches below avoids the deprecation notice.

Classes with #[AllowDynamicProperties] attribute

PHP 8.2 introduces a new attribute in the global namespace named #[AllowDynamicProperties] . Classes declared with this attribute signals PHP to not emit any deprecation notices when setting dynamic properties on objects of that class.

Child classes automatically inherit the #[AllowDynamicProperties] attribute from parent class.

The snippet below declares a User class with #[AllowDynamicProperties] attribute, and does not emit any deprecation notices even though it sets properties dynamically.

+ #[AllowDynamicProperties] class User < private int $uid; >$user = new User(); $user->name = 'Foo';

stdClass and its sub-classes

PHP uses stdClass as the base class when it coerces data to objects, when decoding JSON objects, etc. In PHP 8.2, the #[AllowDynamicProperties] attribute is internally added to the stdClass class. This means setting dynamic properties on stdClass objects or any classes that extend stdClass does not emit dynamic property deprecation notices.

$object = new stdClass(); $object->foo = 'bar';
class User extends stdClass <> $object = new User(); $object->foo = 'bar';

Neither of the snippets above emit dynamic property deprecation notices because the stdClass internally has the #[AllowDynamicProperties] attribute.

Classes with __get and __set magic methods

Classes that declare a __set magic method are excluded from the dynamic property declaration. It might be necessary to couple it with a __get method to create a practically useful class.

class User < public function __set(string $name, mixed $value): void < >> $user = new User(); $user->name = 'test';

The snippet above does not emit a deprecation notice because the User class implements the __set magic method.

Note that setting a dynamic property from within the __set method is still deprecated:

class User < public function __set(string $name, mixed $value): void < $this-> = $value; > > $user = new User(); $user->name = 'test';
Deprecated: Creation of dynamic property User::$name is deprecated in . on line . 

Associating object data with WeakMaps

PHP 8.0 introduced WeakMaps to PHP. Applications that set dynamic properties to associate auxiliary data may consider using WeakMaps. This might improve the clarity and maintainability of the code, while avoiding the dynamic property deprecation notice.

For example, the following snippet stores a dynamic property called processed . This property is not declared on the Event class, and does not belong to the Event class itself.

$event = new Event(); $event->processed = true; // processed);

With WeakMaps, it is possible to associate data in a WeakMap. When the Event object is dropped from the scope, the associated data will be removed automatically.

 $event = new Event(); + $processed_events = new WeakMap(); - $event->processed = true; // processed); + $is_processed = !empty($processed_events[$event]);

Backwards Compatibility Impact

The deprecation notice is emitted on PHP 8.2 and later. In PHP 9.0, dynamic properties will result in a fatal error.

It is possible to programmatically emit a deprecation in older versions in the interest of consistency across multiple PHP versions.

Источник

php — Is it possible to set a class property by name?

Simple question here. I was wondering if it’s possible to access class propertys by it’s name in any way.

$array = array( 'foo' => 'bar', 'hello' => 'world', 'chuck' => 'norris' ); 
class MegaClass 

I was wondering if I could set MegaClass::foo to bar , MegaClass::hello to world and so on, automatically. So, given the array, and given the object, the object is filled. This could be really handy when retreiving data from a form with properties filled.

Answer

Solution:

Well for one thing if you wanted to do MegaClass::foo they would have to be static.

And if they were static you could do:

foreach($array as $key=>$val) 

And if they were not static (but were still public):

foreach($array as $key=>$val)< $MegaClassObject->$key = $val; > 

Answer

Solution:

For non-static members, then

$mc = new MegaClass(); foreach($array as $k=>$v) $mc->$k = $v; 

should do. If that’s what you ask for.

For static you can assign as

but only if the static property is declared.

Answer

Solution:

Something like this, as a minimum, would do what you are asking:

public function setProperties($array) < foreach($array as $key =>$value) < $this->$key = $value; > > 

I would consider flushing it out a little though, perhaps by checking that the property exists and that it has not already been set. You would, of course, modify it to your particular requirements.

public function setProperties($array) < foreach($array as $key =>$value) < if (property_exists(get_called_class(), $key)) < if ($this->$key === NULL) < $this->$key = $value; > > > > 

Answer

Solution:

you can do it with a simple public function and foreach in your class.

class MegaClass < public function setarray(array $array)< foreach($array as $key = >$value)< $this->$key = $value; > > > $array = array( 'foo' => 'bar', 'hello' => 'world', 'chuck' => 'norris' ); $megaclass = new MegaClass(); $megaclass->setarray($array); // this wil set the array to the vars echo $megaclass->foo; // this will output bar 

foreach sets the $array to 2 other vars here that is the $key and $value. in the $key stands foo, hello and chuck and in the $value stands bar, world and norris.

the foreach loop loops every thing one by one and sets it to the right array.

Answer

Solution:

If I understand your question correctly.

$mc = new MegaClass() foreach( $array as $key=>$value ) < $mc->$key = $value; > 

Answer

Solution:

Not 100% sure I understood your question, but assuming your property is not static, you need an instance:

$m = new MegaClass(); echo $m->foo; 

But having a bunch of public fields and setting them externally by looping through some array is probably not the best design. Why not just pass the array to a constructor of MegaClass, and let it initialize its fields internally? Alternatively, have a static factory method that creates a new instance from that array.

Share solution ↓

Additional Information:

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

Оцените статью