如何在PHP中动态实例化一个对象? [英] How to dynamically instantiate an object in PHP?
问题描述
这是正常的代码:
class MyClass {
var $ var1 = null;
var $ var2 = null;
。
。
public function __construct($ args){
foreach($ args as $ key => $ value)
$ this-> $ key = $ value;
}
}
---------------------
$ args =($ _SERVER ['REQUEST_METHOD'] ==POST)? $ _POST:$ _REQUEST;
$ obj = new MyClass($ args);
上述代码工作正常。请注意,请求参数的名称与类 MyClass 的成员准确映射。
但是我们可以这样做:
$ class = 我的课;
$ obj = new $ class;
如果我们这样做,那么我们可以初始化 $ obj 使用 $ args 。
根据这篇文章, $ obj = $ class 应该工作。但它对我来说并不奏效我试过 get_class_vars($ obj)。它抛出一个例外。
谢谢
一些其他魔法方法:
- __ get(一种在调用对象成员时调用的方法)
- __ set
- __ isset
- __ unset
请参阅此键盘,以便您的代码重写为使用您想要的: / p>
<?php
class MyClass {
var $ properties = array();
public function __construct($ args){
$ this-> properties = $ args;
}
public function __get($ name){
echoGet'$ name'\\\
;
if(array_key_exists($ name,$ this-> properties)){
return $ this-> properties [$ name];
}
返回null;
}
}
$ args = array(key1=>value1,key2=>value2);
$ class =MyClass;
$ obj = new $ class($ args);
echokey1:。 $ obj-> KEY1;
?>
Can we dynamically create and initialize an object in PHP? This is the normal code:
class MyClass{
var $var1 = null;
var $var2 = null;
.
.
public function __construct($args){
foreach($args as $key => $value)
$this->$key = $value;
}
}
---------------------
$args = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST : $_REQUEST;
$obj = new MyClass($args);
The above code works fine. Please note that the names of REQUEST parameters are accurately mapped with the members of class MyClass.
But can we do something like this:
$class = "MyClass";
$obj = new $class;
If we can do like this, then can we initialize $obj by using $args.
According to this post, $obj = $class should work. But it does not work for me. I tried get_class_vars($obj). It threw an exception.
Thanks
You have to overload some other magic methods:
- __get (a method that gets called when you call object member)
- __set (a method that gets called when you want to set object member)
- __isset
- __unset
Please see this codepad to see your code rewritten to work with what you want:
<?php
class MyClass{
var $properties = array();
public function __construct($args){
$this->properties = $args;
}
public function __get($name) {
echo "Getting '$name'\n";
if (array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
return null;
}
}
$args = array("key1" => "value1", "key2" => "value2");
$class = "MyClass";
$obj = new $class($args);
echo "key1:". $obj->key1;
?>
这篇关于如何在PHP中动态实例化一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!