Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 996
Gnahzllib Avatar asked Sep 11 '25 22:09

Gnahzllib


1 Answers

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
like image 176
cb0 Avatar answered Sep 13 '25 13:09

cb0