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:
<?php
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:
<?php
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!
Watch a video course
Learn object oriented PHP
Alternatively, you can use the ->{}
<?php
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.
<?php
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.