An idiom commonly used in OO languages like Python and Ruby is instantiating an object and chaining methods that return a reference to the object itself, such as:
s = User.new.login.get_db_data.get_session_data
In PHP, it is possible to replicate this behavior like so:
$u = new User();
$s = $u->login()->get_db_data()->get_session_data();
Attempting the following results in syntax error, unexpected T_OBJECT_OPERATOR
:
$s = new User()->login()->get_db_data()->get_session_data();
It seems like this could be accomplished using static methods, which is probably what I'll end up doing, but I wanted to check the lazyweb: Is there actually a clean, simple way to instantiate PHP classes "inline" (as shown in the above snippet) for this purpose?
If I do decide to use static methods, is it too sorcerous to have a class's static method return an instantiation of the class itself? (Effectively writing my own constructor-that-isn't-a-constructor?) It feels kind of dirty, but if there aren't too many scary side effects, I might just do it.
I guess I could also pre-instantiate a UserFactory with a get_user() method, but I'm curious about solutions to what I asked above.