R
R
romaaa322018-09-06 21:42:28
PHP
romaaa32, 2018-09-06 21:42:28

How to call a class in another class?

How to call class A in class B to use it in multiple methods?
Class B calls class A in many methods. Can it be called once, and in methods only access the necessary methods from class A?
Normally explained what I want?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bkosun, 2018-09-06
@romaaa32

1. Dependency injection
2. Inheritance (for similar objects)
Dependency injection example:

class A
{
    public function print()
    {
        return 'Some text...';
    }
}

Class B
{
    protected $a;

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

    public function print(){
        return $this->a->print();
    }
}

$a = new A();

$b = new B($a);

echo $b->print(); // Some text...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question