How to create child object from existing parent object
I have following php class
class User implements IUser
{
public function __construct($i_objParent = NULL)
{
}
}
When I login successfully I create object of User class.
There is another class named Student class as follows which extends User Class
class Student extends User
{
public function __construct($i_objParent = NULL)
{
parent::construct($i_objParent);
}
}
Now as I said eariler I开发者_StackOverflow already have object of User class
how can I construct Student object
from existing User Class
.
I think it may be possible by passing existing User class
object to constructor of child class here Student class
object?
Also, Is above approach OK?
As you cannot cast objects in php ( well there are really ugly hacks that work, but i would avoid them ).
Instead there are two ways:
- create a factory class which takes the
User
instance in returns you newStudent
instance with all the data transfered - use Decorator pattern , which would call methods on
User
instance
Actually there is third way ( one that i would use ) : do not do this.
PHP is not the language for DCI development paradigm. IMHO this whole construction makes no sense. User
and Student
are not interchangeable.
One class extending another does not have anything to do with parent / child relationship between them. It's a architecture solution, that allows you to re-use functionality, save on duplicating the code. I am not aware of any automatic call that would get the object that extends User class. I would create a function
public function getChild($type)
{
switch($type)
{
case "user":
return new Student();
break;
case "teacher":
return new Teacher();
break;
}
}
It's best to have all classes either abstract or leaf, to avoid such problems. Inheritance cannot be applied to this design, You should change it to either
1 - Using User as a property of Student not as it's parent (which may end up in using Decorator pattern) 2 - Defining User as an abstract class and creating a Student object from the beginning
As you know polymorphic works upside down, and even object casting would not help you in this case.
Here is the same problem on java
精彩评论