众所周知,在JavaScript中创建匿名对象很容易,如下面的代码:
var object = {
p : "value",
p1 : [ "john", "johnny" ]
};
alert(object.p1[1]);
输出:
an alert is raised with value "johnny"
这个技巧能在PHP中应用吗?我们能在PHP中创建匿名对象吗?
众所周知,在JavaScript中创建匿名对象很容易,如下面的代码:
var object = {
p : "value",
p1 : [ "john", "johnny" ]
};
alert(object.p1[1]);
输出:
an alert is raised with value "johnny"
这个技巧能在PHP中应用吗?我们能在PHP中创建匿名对象吗?
class stdClass {
public function __construct(array $arguments = array()) {
if (!empty($arguments)) {
foreach ($arguments as $property => $argument) {
if(is_numeric($property)):
$this->{$argument} = null;
else:
$this->{$property} = $argument;
endif;
}
}
}
public function __call($method, $arguments) {
$arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
if (isset($this->{$method}) && is_callable($this->{$method})) {
return call_user_func_array($this->{$method}, $arguments);
} else {
throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
}
}
public function __get($name){
if(property_exists($this, $name)):
return $this->{$name};
else:
return $this->{$name} = null;
endif;
}
public function __set($name, $value) {
$this->{$name} = $value;
}
}
$obj1 = new stdClass(['property1','property2'=>'value']); //assign default property
echo $obj1->property1;//null
echo $obj1->property2;//value
$obj2 = new stdClass();//without properties set
echo $obj2->property1;//null
Object var = new Object() { ... };
-- C++:class { ... } var;
- TheOperator