Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic class property $$value in php

How can i reference a class property knowing only a string?

class Foo {     public $bar;      public function TestFoobar()     {         $this->foobar('bar');     }      public function foobar($string)     {          echo $this->$$string; //doesn't work     } } 

what is the correct way to eval the string?

like image 448
Cameron A. Ellis Avatar asked May 12 '09 18:05

Cameron A. Ellis


People also ask

What is dynamic property PHP?

Dynamic properties are property that are not declared in the class, but in the code in your class, you want to use a not declared property: class User { public string $name; public function __construct($name="", $age = 0) { $this->name = $name; // Assigns the not existent property age.

How Can Get object property value in PHP?

The get_object_vars() function is an inbuilt function in PHP that is used to get the properties of the given object. When an object is made, it has some properties. An associative array of properties of the mentioned object is returned by the function. But if there is no property of the object, then it returns NULL.

What are class properties in PHP?

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.

What is dynamic property?

1.2 Basic Dynamic Properties and Their Significance Theoretically, it can be defined as the ratio of stress to strain resulting from an oscillatory load applied under tensile, shear, or compression mode.


2 Answers

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

echo $this->$string; 
like image 140
Antonio Haley Avatar answered Sep 20 '22 12:09

Antonio Haley


If you want to use a property value for obtaining the name of a property, you need to use "{" brackets:

$this->{$this->myvar} = $value; 

Even if they're objects, they work:

$this->{$this->myobjname}->somemethod(); 
like image 39
Rick Avatar answered Sep 21 '22 12:09

Rick