Reputation:
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
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
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