Reputation: 1408
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 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?
Upvotes: 7
Views: 8989
Reputation: 150
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
Upvotes: 0
Reputation: 58444
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:
User
instance in returns you new Student
instance with all the data transferedUser
instanceActually 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.
Upvotes: 3
Reputation: 3414
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;
}
}
Upvotes: 0