Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create child object from existing parent object

Tags:

oop

php

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?

like image 205
Bharat Patil Avatar asked Aug 11 '11 12:08

Bharat Patil


1 Answers

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 new Student 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.

like image 189
tereško Avatar answered Nov 15 '22 08:11

tereško