Warning: file_put_contents(): Only 0 of 8322 bytes written, possibly out of free disk space in system/classes/filecache.php line 154
Warning: file_put_contents(): Only 0 of 303 bytes written, possibly out of free disk space in system/classes/filecache.php line 157
Fluid PHP BaseObject Class - RedAlt

Sometimes you want to get an instance of an object in PHP and then use it immediately. The problem is that PHP syntax doesn't typically allow this. To explain, what you would really like to do is this:

$result = (new DB('connection string'))->query('SELECT 1');

Obviously, that doesn't work. But there is a way to get what you want by using a kind of factory method.

Normally, you have this:
class DB {...}

And you must do this:
$db = new DB('connection string'); $result = $db->query('SELECT 1');

If you have a class that extends BaseObject:
class DB extends BaseObject {...}

You can do this instead:
$result = DB::create('connection string')->query('SELECT 1');

The static create() method becomes available to any class that extends BaseObject, and can pass through parameters to the derived class constructor.
class BaseObject { public static function create() { $class = get_called_class(); $args = func_get_args(); $r_class = new \ReflectionClass($class); return $r_class->newInstanceArgs( $args ); } }

Want to suggest improvements? Please fork.

Comments

There are no comments on this post.