开发者

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()
  开发者_如何学JAVA  {
        return new User();
    }

    public function get()
    {
        $this->name = 'Foo Bar';
        $this->email = 'foo.bar@baz.com';
    }
}


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();


Have your get return $this;.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜