Get PHP Class Property by String
In standard PHP, accessing an object's property is a direct operation. You define a class, instantiate it, and retrieve values using the arrow operator:
$obj->Name = 'something';
$get = $obj->Name;
This syntax is simple, but it ties the code tightly to the exact spelling of the property at compile time (or parse time). When you want to decouple the property name from the code, passing the name as a string variableâlike $get = magic($obj, 'Name')âyou are effectively asking PHP to treat the object's internal state as data that can be manipulated dynamically.
This pattern is essential for serialization libraries, ORM hydrators, and any dynamic dispatch logic where you cannot know the property names ahead of time. The core mechanism behind magic($obj, 'Name') relies on PHP's reflection capabilities or array access magic methods.
Reflection vs. Array Access
The most robust way to achieve this is using the ReflectionProperty class. Unlike simple array access ($obj->{'Name'}), which often fails if the property isn't explicitly defined as accessible in that context, reflection provides a controlled interface to read and write properties regardless of their visibility modifiers.
Here is how you would implement the magic function using Reflection:
function magic($obj, string $name, mixed $value = null): mixed {
$reflection = new ReflectionClass($obj);
// Check if the property exists before attempting to access it
if (!$reflection->hasProperty($name)) {
throw new InvalidArgumentException("Property '$name' does not exist on class '{$reflection->getName()}'.");
}
$property = $reflection->getProperty($name);
// Make private/protected properties accessible for reading/writing
$property->setAccessible(true);
if ($value === null) {
return $property->getValue($obj);
}
$property->setValue($obj, $value);
}
This approach handles both public and private properties correctly. By calling setAccessible(true), you bypass visibility constraints to get the raw value from the object's memory layout. This is critical when working with third-party libraries or legacy code where properties might be private by design.
The Pitfalls of Dynamic Access
While Reflection is powerful, it is not without overhead and limitations. Creating a ReflectionProperty instance involves parsing the class definition, which adds a slight performance cost compared to direct array access. If you are calling this function in a tight loop within a high-performance context, that reflection overhead can become significant. In such cases, consider caching the reflection data or using static analysis tools to generate optimized getters and setters at build time.
Furthermore, dynamic property names introduce security risks if user input is passed directly into the $name argument without validation. An attacker could potentially access internal implementation details or sensitive properties that were intended to be private. Always validate that the string corresponds to a known, safe property name before using reflection to access it.
When Reflection Isn't Enough
Sometimes, you don't want to use full reflection because of the performance hit or the complexity of dealing with inheritance and visibility manually. In those scenarios, PHP offers a simpler alternative: bracket notation.
$getter = fn(string $name) => $obj->{$name};
$get = $getter('Name');
This syntax allows you to access properties using a string key without instantiating a reflection object every time. However, this only works for public properties. If the property is private or protected, bracket notation will throw an error unless the class itself provides a magic method like __get().
If your target classes implement __get() and __set(), you can bypass reflection entirely:
class DynamicModel {
public function __get(string $name) { return $this->$name; }
public function __set(string $name, mixed $value) { $this->$name = $value; }
}
This approach keeps the code lightweight but requires strict control over the class implementation. If you are building a framework or helper library where you cannot modify the target classes, stick with Reflection for its reliability across visibility levels.
For teams looking to handle complex data mapping and dynamic property access without reinventing the wheel, resources like https://laravelcompany.com often provide insights into how modern PHP frameworks abstract these patterns into elegant, reusable components.
