E
E
EvGenius Karlonius2017-03-08 19:41:04
PHP
EvGenius Karlonius, 2017-03-08 19:41:04

What is the right way, if possible, to call a class inside another class?

In class " B " I can't call a function of class " A ". To call it, you need to redefine it $a = new A() in the " B " class. How can I call so as not to override? or maybe you need to somehow correctly describe the class " A "?
index.php

$a = new A();
$b = new B();

A.php
class A {	
  public function print_tst() {
    echo "tst";
  }
}

b.php
class B {	
  function __construct() {
    $a->print_tst();
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
ThunderCat, 2017-03-08
@BloodKarl

1) static class A
here

class B {	
  function __construct() {
    $a->print_tst();
  }
}
who and how should guess what a is an instance of class A? respectively:
2) When calling, you need to create an instance of class A, otherwise such a call does not make sense.
3) DI - pass the created instance A to the constructor

A
Axian Ltd., 2017-03-08
@AxianLTD

Create an instance of class "a" global.

T
T_y_l_e_r, 2017-03-08
@T_y_l_e_r

__construct($a)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question