Object-oriented – should I extend or create instance of the class

object-orientedPHP

I have two classes Class A and Class B

In Class A, I have three methods that perform the save, delete and select operation based upon the object I pass them. In Class B I perform the logic operations, such as modification to the property of the object before being passed to the methods of Class A.

My problem is in Class B, should it extend Class A, and call the methods of class A , by parent::methodName or create instance of class A and then call

Class A does not includes any property just methods.

class A{
  public function save($obj){
         //code here
    }

   public function delete($obj){
         //code here
    }

    public function select($obj){
         //code here
    }
 }

//Should I extend class A, and call the method by parent::methodName($obj)
or create an instance of class A, call the method $instanceOfA->methodName($obj);

 class B extends A{

    public function checkIfHasSaved($obj){
         if($obj->saved == 'Yes'){
                  parent::save($obj);   //**should I call the method like this**
                 $instanceOFA = new A();   //**or create instance of class A and call without extending class A** 
                 instanceOFA->save($obj);
            }
             //other logic operations here
      }

 }

Best Answer

The examples given by you could have had meaningful class names, this would favor much better responses.

Since class A does not have any properties, it is safe to use methods from the instance you already have:

class B extends A
{
    public function checkIfHasSaved($obj)
    {
        if($obj->saved)
            $this->save($obj);
    }
}

Another alternative would be to use Dependency injection instead:

class B
{
    protected $a;

    public function __construct(A $theObject)
    {
        $this->a = $theObject;
    }

    public function checkIfHasSaved($obj)
    {
        if($obj->saved)
            $this->a->save($obj);
    }
}
Related Topic