Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between extend a class and create instance in another class in php

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?

like image 420
Md Zannatul Haque Siam Avatar asked Oct 18 '22 20:10

Md Zannatul Haque Siam


1 Answers

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;
    }
}
like image 177
Machavity Avatar answered Oct 21 '22 05:10

Machavity