Php new Class()和ReflectionClass::newInstance()之间的区别?

Php new Class()和ReflectionClass::newInstance()之间的区别?,php,Php,我在看一个处理类和对象的程序,我发现这行代码很混乱 Class::newInstance()和newclass()之间有区别吗 我阅读了文档,它似乎没有提到任何不同的内容,所以我假设它是相同的?语句创建了一个名为Class的类的新对象实例 Class::newInstance()调用名为Class的类上的static方法。在您的教程中,最有可能调用并返回的是newclass()。 类中需要存在静态函数newInstance。它不是afaik中所有php对象的本机对象 这应该说明: class F

我在看一个处理类和对象的程序,我发现这行代码很混乱

Class::newInstance()
newclass()
之间有区别吗

我阅读了文档,它似乎没有提到任何不同的内容,所以我假设它是相同的?

语句创建了一个名为
Class
的类的新对象实例

Class::newInstance()
调用名为
Class
的类上的
static
方法。在您的教程中,最有可能调用并返回的是
newclass()
。 类中需要存在静态函数
newInstance
。它不是afaik中所有php对象的本机对象

这应该说明:

class Foo
{
    private $bar = null;

    public static function newInstance($args){
        return new self($args);
    }

    public function __construct($bar = "nothing")
    {
        $this->bar = $bar;
    }

    public function foo()
    {
        echo "Foo says:" . $this->bar . "\n";
    }
}

//create using normal new Classname Syntax
$foo1 = new Foo("me");
$foo1->foo();

//create using ReflectionClass::newInstance
$rf   = new ReflectionClass('Foo');
$foo2 = $rf->newInstance();
$foo2->foo();

//create using refelction and arguments
$foo3= $rf->newInstanceArgs(["happy"]);
$foo3->foo();

//create using static function 
$foo4 = Foo::newInstance("static");
$foo4->foo();
将输出:

Foo says:me
Foo says:nothing
Foo says:happy
Foo says:static

一个区别是例外thrown@MarkBaker因此,这两种方法都可以用来调用一个类,但例外情况不同?您还可以使用
ReflectionClass::newInstance()
克隆现有实例(在调用点使用它的所有属性值,绕过构造函数)如果您使用实例而不是简单的类名称为
class::newInstance
创建ReflectionClass,那么有一个名为
class
的方法吗?现在,我知道您需要声明
newInstance
,但它可以是其他名称还是必须声明为
newInstance
?那么它们只是调用类的不同方式?为什么不使用最简单的方法呢?你可以随意命名函数
newMyInstance
或其他内容。这主要取决于用例。每种可能性都有它的优点。例如,如果您不知道参数的确切数量,可以使用选项3($foo3)并传入数组。如果你想了解更多关于这个主题的信息,你应该阅读关于创造模式的内容。谢谢你的帮助!