php - How to create child object from existing parent object
Get the solution ↓↓↓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 ofUser class
how can I constructStudent object
from existingUser Class
.
I think it may be possible by passing existingUser class
object to constructor of child class hereStudent class
object?
Also, Is above approach OK?
Answer
Solution:
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
andStudent
are not interchangeable.
Answer
Solution:
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;
}
}
Answer
Solution:
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.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.