'Accessing associative array by object
It's possible to access associative array by object? I tried to use __toString
method, but it isn't automatically called.
class ColumnItem {
private string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function __toString() {
return $this->name;
}
}
...
$array = ['Name' => 'John'];
$nameItem = new ColumnItem('Name');
//$name = $array[$nameItem]; // PHP Fatal error: Uncaught TypeError: Illegal offset type
$name = $array[strval($nameItem)];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|