Gnahzllib
Gnahzllib

Reputation: 101

Difference between new Class() and ReflectionClass::newInstance()?

I was watching a tutorial that deals with class and objects, and I came across this line of code that was confusing.

Is there a difference between Class::newInstance() and new Class()?

I read the documentation, and it did not appear to mention anything different so I assumed it's the same?

Upvotes: 4

Views: 1686

Answers (1)

cb0
cb0

Reputation: 8613

The new Class() statement created a new object instance of class named Class.

The Class::newInstance() calls a static method on class named Class. Which in your tutorial most likely will call and return new Class(). The static function newInstance needs to be present in the class. It is not native to all php objects afaik.

This should make it clear:

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 reflection and arguments
$foo3= $rf->newInstanceArgs(["happy"]);
$foo3->foo();

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

Will output:

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

Upvotes: 2

Related Questions