How can one access a variable or array in a class with a runtime-defined class name in PHP?
When trying to access a variable or array in a class with a runtime-defined class name in PHP, you can use variable variables to achieve this. By using the double dollar sign ($$) followed by the runtime-defined class name, you can dynamically access the variable or array within that class.
class MyClass {
public $data = ['value1', 'value2', 'value3'];
}
$className = 'MyClass';
$instance = new $className();
// Accessing the array in the class with a runtime-defined class name
$dynamicArray = $instance->data;
print_r($dynamicArray);
Keywords
Related Questions
- How can the use of eval strings in PHP be avoided when dynamically calling functions based on predefined names or indexes?
- Is using mysqli_result::close to clear memory a recommended practice to avoid duplicate database entries in PHP?
- What are the potential security risks of executing a PHP script from a remote server?