5

First file:

class Class_one {

    public function __construct() {

    }

    public function show_name() {
        echo "My Name is Siam";
    }

    public function show_class() {
        echo "I read in class 7";
    }

}

Second file:

<?php

require_once './Class_one.php';

class Class_two {

    public $class_one;

    public function __construct() {
        $aa = new Class_one();
        $this->class_one = $aa;
    }

    public function history() {
        $this->class_one->show_name();
    }

}

$ab = new Class_two();
$ab->history();

What will happen if i don't instantiate class_one in class_two and extend class_one into class_two? Is there any difference?

Dekel
  • 60,707
  • 10
  • 101
  • 129

2 Answers2

2

There's only one potential gotcha here: Class_two won't have direct access to Class_one private/protected methods and variables. That can be a good thing (encapsulation is where a class does some specific task and you don't want children to interfere with it), but it can also mean you can't get to the data you need.

I would suggest you do Class_two as a dependency injection (as shown in your example), however

class Class_two {

    public $class_one;

    public function __construct(Class_one $class) {
        $this->class_one = $class;
    }
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
1

It should be a semantic difference:

  • You use inheritance when relationship between two classes can be expressed with to be verb. For example: My Ford is a Car
  • You use association/composition when relationship between two classes can be expressed with to have verb. For example: My car has an engine.

Above rules should be the first consideration when choosing inheritance or association in object-oriented programming. There've been always discussion about avoiding inheritance, and some will argue that you should choose composition over inheritance. See this other Q&A: Prefer composition over inheritance?

In terms of pure coding, as @Machavity on his answer has already said, there could be accessibility limitations when using composition instead of inheritance, but I wouldn't decide which approach to use based on member accessibility.

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206