$test = new Test(['id' => 5, 'name' => 'root']);
echo $test->id; // Выводит 5;
echo $test->name; // Выводит root;
<?php
class Test {
public function __construct(array $input)
{
foreach ($input as $key => $val) {
$this->{$key} = $val;
}
}
}
$test = new Test(['id' => 5, 'name' => 'root']);
var_dump($test->id);
var_dump($test->name);
$std = (object)['id' => 5, 'name' => 'root'];
var_dump($std);
var_dump($std->id);
var_dump($std->name);
/*
object(stdClass)#2 (2) {
["id"]=>
int(5)
["name"]=>
string(4) "root"
}
*/
$array = ['id' => 5, 'name' => 'root'];
$object = (object) $array;
echo $object->id; // -> 5
class Test {
private $data = [];
public function __construct($arr) {
$this->data = $arr;
}
public function __get($name)
{
return $this->data[$name] ?? 'no data';
}
}
$test = new Test(['id' => 5, 'name' => 'root']);
echo $test->name; // -> 'root'
echo $test->foo; // -> 'no data'