Changing Object Class on the Fly - Use Case
Here's another use-case for changing an object's class on the fly: upgrading a class to a version that provides debugging and logging, so that developers can see extra logs while actually using the core, logical functionality that the users themselves see.
The Class You Want To Morph Into Another
And the procedure is fairly simple. You start with your original class...
class User { protected $Id; protected $Name; protected $Password; protected $PostsPerPage;}
The New Class Using the Old Class
And then you want a new class for the same variable $user
, since you have a new plugin. Remember to use extends
to inherit...
class UserWithPrivilege extends User { [...] protected $Visible;}
Instantiating a Morphed Version of an Object using an Old Class Version of Said Object
And since $user
already has data, you'll need to make a constructor for UserWithPrivilege
that takes the old $user
and reimplements it locally. I.E....
class UserWithPrivilege extends User { public function __construct($user) { $this->Id = $user->Id; # and for all other old attributes) }}
With this, you'll be able to convert an old class, to a newer version of that class, all using the same variable and without doing much in terms of heavy CPU processing.