简体   繁体   English

如何在PHP中动态实例化对象?

[英]How to dynamically instantiate an object in PHP?

Can we dynamically create and initialize an object in PHP? 我们可以在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 . 请注意, REQUEST参数的名称与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 . 如果我们可以这样做,那么我们可以使用$ args初始化$ obj

According to this post , $obj = $class should work. 根据这篇文章$ obj = $ class应该有效。 But it does not work for me. 但它对我不起作用。 I tried get_class_vars($obj) . 我试过get_class_vars($ obj) It threw an exception. 它引发了一个例外。

Thanks 谢谢

It's more a comment, but I leave it here more prominently: 这是一个评论,但我更加突出地留在这里:

$class = "MyClass";
$obj = new $class($args);

This does work. 这确实有效。 See new Docs . 查看new 文档

You can use Reflection to instanciate an object with parameters. 您可以使用Reflection来使用参数实例化对象。

<?php

class Foo {
    protected $_foo;
    protected $_bar;

    public function __construct($foo, $bar)
    {
        $this->_foo = $foo;
        $this->_bar = $bar;
    }

    public function run()
    {
        echo $this->_foo . ' ' . $this->_bar . PHP_EOL;
    }
}

$objectClass = 'Foo';
$args = array('Hello', 'World');

$objectReflection = new ReflectionClass($objectClass);
$object = $objectReflection->newInstanceArgs($args);

$object->run();

See Reflection on php manual. 请参阅php手册上的反思

You have to overload some other magic methods : 你必须重载一些其他魔术方法

  • __get (a method that gets called when you call object member) __get(调用对象成员时调用的方法)
  • __set (a method that gets called when you want to set object member) __set(当您想要设置对象成员时调用的方法)
  • __isset __isset
  • __unset __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;
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM