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