Php get object property by string

Get PHP class property by string

If you want to access the property without creating an intermediate variable, use the <> notation:

That also allows you to build the property name in a loop for example:

Solution 3

What you’re asking about is called Variable Variables. All you need to do is store your string in a variable and access it like so:

$Class = 'MyCustomClass'; $Property = 'Name'; $List = array('Name'); $Object = new $Class(); // All of these will echo the same property echo $Object->$Property; // Evaluates to $Object->Name echo $Object->; // Use if your variable is in an array 

Solution 4

Something like this? Haven’t tested it but should work fine.

function magic($obj, $var, $value = NULL) < if($value == NULL) < return $obj->$var; > else < $obj->$var = $value; > > 

Solution 5

Just store the property name in a variable, and use the variable to access the property. Like this:

$name = 'Name'; $obj->$name = 'something'; $get = $obj->$name; 

5: Properties And Methods In OOP PHP | Object Oriented PHP Tutorial For Beginners | mmtuts

8: Static Properties And Methods In OOP PHP | Object Oriented PHP Tutorial | PHP Tutorial | mmtuts

3 Property and Method in OOP PHP

PHP Classes & Objects - Typed Properties - Constructors & Destructors - Full PHP 8 Tutorial

PHP Tutorial - access (stdClass) Object property named as variable

PHP : Get PHP class property by string

How to PHP : Get PHP class property by string

Daniel A. White

I’m a Software Engineer in Indianapolis, Indiana who is #SOreadytohelp! Member of the .NET Foundation.

Updated on December 04, 2021

Comments

$obj->Name = 'something'; $get = $obj->Name; 
magic($obj, 'Name', 'something'); $get = magic($obj, 'Name'); 

Ólafur Waage

The question is how to get a class property (variable) when the name is contained in a string (variable). Or did I misread the question?

Marco Demaio

This is very bad advice, the eval() function is a very dangerous tool and will leave you hugely vulnerable to injection attacks. blog.highub.com/php/php-core/php-eval-is-evil should give you some information.

This is the only way if you want to access an array value $this->[$name] , otherwise $this->$property[$name] will throw an error

@goyote: It depends values and PHP version. In 5.3 it triggers an E_NOTICE because the property cannot be found, rather than an «error», since it is still valid PHP syntax. It’s possible that $this->$property[$name] might actually succeed, although this is likely to be a bug. $name is silently cast to an integer. In the case of a non-numeric string this is 0 . Then this string index of the value of $property is used as the property name. If $property holds the value «abc», then this will refer to the property $this->a (index 0). If there is such a property then this will succeed.

@goyote: However, in PHP 5.4, a non-numeric string index is not silently cast to the integer 0, it will trigger an E_WARNING.

Источник

Get PHP class property by string

In PHP, you can use the $ operator to access an object’s properties by name. For example, if you have a class MyClass with a property myProperty , you can access the property like this:

 class MyClass < /** * @var int */ private int $myProperty; public function __construct( ) < $this->myProperty = 0; > public function getMyProperty( ): int < return $this->myProperty; > public function setMyProperty(int $value): void < $this->myProperty = $value; > > $object = new MyClass(); $propertyValue = $object->getMyProperty(); echo "The value of the myProperty is: " . $propertyValue;

If you have the property name as a string, you can use the $<> syntax to access the property by name:

 class MyClass < public $myProperty = "Hello, world!"; > $object = new MyClass(); $propertyName = 'myProperty'; $propertyValue = $object->$propertyName>; // use the -><> operator to access the property dynamically echo $propertyValue; // Output: Hello, world!

Alternatively, you can use the -><>

 class MyClass < /** * @var int */ private int $myProperty; public function __construct( ) < $this->myProperty = 0; > public function getMyProperty( ): int < return $this->myProperty; > public function setMyProperty(int $value): void < $this->myProperty = $value; > > $object = new MyClass(); $propertyName = 'getMyProperty'; echo $propertyValue = $object->$propertyName>();

It’s also worth noting that you can also use __get magic method in class to return the property value.

 class MyClass < public $myProperty; public function __get($property) < if (property_exists($this, $property)) < return $this->$property; > else < echo "The property '$property' does not exist in this class."; > > > $object = new MyClass(); $propertyName = 'nonExistentProperty'; $propertyValue = $object->$propertyName; // this will trigger __get // Output: The property 'nonExistentProperty' does not exist in this class.

Keep in mind that this will only work if the property exists in the class and is not protected or private.

Источник

Get PHP class property by string

How do I get a property in a PHP based on a string? I’ll call it magic . So what is magic ?

$obj->Name = 'something'; $get = $obj->Name; 
magic($obj, 'Name', 'something'); $get = magic($obj, 'Name'); 

Php Solutions

Solution 1 — Php

Or, if you have control over the class, implement the ArrayAccess interface and just do this

Solution 2 — Php

If you want to access the property without creating an intermediate variable, use the <> notation:

$something = $object->'something'>; 

That also allows you to build the property name in a loop for example:

for ($i = 0; $i < 5; $i++) $something = $object->'something' . $i>; // . > 

Solution 3 — Php

What you’re asking about is called Variable Variables. All you need to do is store your string in a variable and access it like so:

$Class = 'MyCustomClass'; $Property = 'Name'; $List = array('Name'); $Object = new $Class(); // All of these will echo the same property echo $Object->$Property; // Evaluates to $Object->Name echo $Object->$List[0]>; // Use if your variable is in an array 

Solution 4 — Php

Something like this? Haven’t tested it but should work fine.

function magic($obj, $var, $value = NULL) < if($value == NULL) < return $obj->$var; > else < $obj->$var = $value; > > 

Solution 5 — Php

Just store the property name in a variable, and use the variable to access the property. Like this:

$name = 'Name'; $obj->$name = 'something'; $get = $obj->$name; 

Solution 6 — Php

There might be answers to this question, but you may want to see these migrations to PHP 7

backward incompatible change

Solution 7 — Php

It is simple, $obj->Name> the curly brackets will wrap the property much like a variable variable.

This was a top search. But did not resolve my question, which was using $this. In the case of my circumstance using the curly bracket also helped.

example with Code Igniter get instance

in an sourced library class called something with a parent class instance

$this->someClass='something'; $this->someID=34; 

the library class needing to source from another class also with the parents instance

echo $this->CI->this->someClass>->this->someID>; 

Solution 8 — Php

Just as an addition: This way you can access properties with names that would be otherwise unusable

$x = new StdClass; 

$prop = 'a b'; $x->$prop = 1; $x-> = 2; var_dump($x);

object(stdClass)#1 (2) < ["a b"]=>int(1) ["x y"]=> int(2) >

(not that you should, but in case you have to).
If you want to do even fancier stuff you should look into http://de.php.net/reflection»>reflection

Solution 9 — Php

In case anyone else wants to find a deep property of unknown depth, I came up with the below without needing to loop through all known properties of all children.

For example, to find $foo->Bar->baz->bam , given an object ( $foo ) and a string like «Bar->baz->bam».

trait PropertyGetter < public function getProperty($pathString, $delimiter = '->') < //split the string into an array $pathArray = explode($delimiter, $pathString); //get the first and last of the array $first = array_shift($pathArray); $last = array_pop($pathArray); //if the array is now empty, we can access simply without a loop if(count($pathArray) == 0)< return $this->$first>->$last>; > //we need to go deeper //$tmp = $this->Foo $tmp = $this->$first>; foreach($pathArray as $deeper) < //re-assign $tmp to be the next level of the object // $tmp = $Foo->Bar --- then $tmp = $tmp->baz $tmp = $tmp->$deeper>; > //now we are at the level we need to be and can access the property return $tmp->$last>; > > 

And then call with something like:

$foo = new SomeClass(); // this class imports PropertyGetter trait echo $foo->getProperty("bar->baz->bam"); 

Solution 10 — Php

Here is my attempt. It has some common ‘stupidity’ checks built in, making sure you don’t try to set or get a member which isn’t available.

You could move those ‘property_exists’ checks to __set and __get respectively and call them directly within magic().

 class Foo < public $Name; public function magic($member, $value = NULL) < if ($value != NULL) < if (!property_exists($this, $member)) < trigger_error('Undefined property via magic(): ' . $member, E_USER_ERROR); return NULL; > $this->$member = $value; > else < if (!property_exists($this, $member)) < trigger_error('Undefined property via magic(): ' . $member, E_USER_ERROR); return NULL; > return $this->$member; > > >; $f = new Foo(); $f->magic("Name", "Something"); echo $f->magic("Name") , "\n"; // error $f->magic("Fame", "Something"); echo $f->magic("Fame") , "\n"; ?> 

Solution 11 — Php

What this function does is it checks if the property exist on this class of any of his child’s, and if so it gets the value otherwise it returns null. So now the properties are optional and dynamic.

/** * check if property is defined on this class or any of it's childes and return it * * @param $property * * @return bool */ private function getIfExist($property) < $value = null; $propertiesArray = get_object_vars($this); if(array_has($propertiesArray, $property))< $value = $propertiesArray[$property]; > return $value; > 
const CONFIG_FILE_PATH_PROPERTY = 'configFilePath'; $configFilePath = $this->getIfExist(self::CONFIG_FILE_PATH_PROPERTY); 

Solution 12 — Php

$classname = "myclass"; $obj = new $classname($params); $variable_name = "my_member_variable"; $val = $obj->$variable_name; //do care about the level(private,public,protected) $func_name = "myFunction"; $val = $obj->$func_name($parameters); 

why edit: before : using eval (evil) after : no eval at all. being old in this language.

Источник

Читайте также:  Sudo apt install php libapache2 mod php
Оцените статью