user623520
user623520

Reputation:

Factory method problem

Why does User::factory() create an object, but User::factory()->get() not? What am I doing wrong? Thanks!

class User {

    public $name;
    public $email;

    public static function factory()
    {
        return new User();
    }

    public function get()
    {
        $this->name = 'Foo Bar';
        $this->email = '[email protected]';
    }
}

Upvotes: 1

Views: 172

Answers (3)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

The get method is not returning anything. You can add:

   return $this;

as the last line of the get method if you want it to return an object.

Upvotes: 1

quasistoic
quasistoic

Reputation: 4687

Have your get return $this;.

Upvotes: 1

Yet Another Geek
Yet Another Geek

Reputation: 4289

User::factory() creates an object because it returns an object made by an constructor. User::factory()->get() creates an object and calls the get method, but the get method do not return the object, so it gets destructed afterwards. If you want your get method to return the object, just use return $this; at the end of the method. Otherwise assign the returned object to variable and then call get:

$user = User::factory();
$user->get();

Upvotes: 3

Related Questions