W3docs

Get PHP class property by string

In PHP, you can use the $ operator to access an object's properties by name.

In PHP, you can use the -> operator to access an object's properties. For example, if you have a class MyClass with a property myProperty, you can access the property value like this:

Example of using the -> operator to access an object's properties in PHP

<?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 $object->{$propertyName} syntax to access the property dynamically:

Example of using dynamic property access in PHP

<?php

class MyClass
{
  public $myProperty = "Hello, world!";
}

$object = new MyClass();
$propertyName = 'myProperty';
$propertyValue = $object->{$propertyName}; // access property dynamically using a string variable

echo $propertyValue; // Output: Hello, world!

Alternatively, you can use the same dynamic syntax to call methods:

Example of using dynamic method invocation in PHP

<?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();
$methodName = 'getMyProperty';
echo $propertyValue = $object->{$methodName}();

It's also worth noting that you can use the __get magic method in a class to handle inaccessible or non-existent properties:

Example of using the __get magic method in PHP

<?php

class MyClass
{
  private $myProperty = "Hello, world!";

  public function __get($name)
  {
    if (property_exists($this, $name)) {
      return $this->$name;
    } else {
      echo "The property '$name' does not exist in this class.";
    }
  }
}

$object = new MyClass();
$propertyValue = $object->myProperty; // Triggers __get because the property is private

echo $propertyValue; // Output: Hello, world!

Keep in mind that __get is only triggered for inaccessible (private or protected) or non-existent properties. It will not be called for public properties.