Calling a PHP class from another class

really simple, I guess, but why does the following not work? I assume this is a matter of visibility when class2 is not displayed inside class1. Yes, I get the error "Calling a member function on a non-object."

class class1 { function func1() { $class2->func3(); } function func2() { $this->func1(); } } class class2 { function func3() { echo "hello!"; } } $class1 = new class1(); $class2 = new class2(); $class1->func1; 

If anyone can help me, I would be very grateful. I searched around for a while, but I have many examples of others trying to create new classes inside other classes and the like, and not for this particular problem.

You would be right in thinking that I do not do much with classes!

+4
source share
4 answers

PHP is not like JavaScript, so your $class2 is undefined:

The scope of a variable is the context in which it is defined. For the most part, all PHP variables have only one scope. The required files are included in this single scope [...]. A local function is introduced in user-defined functions. Any variable used inside a function is, by default, limited to the scope of local functions.

Source: http://php.net/manual/en/language.variables.scope.php

In other words, in PHP there is only a global scope scope and function / method. So either pass the instance of $class2 to the method as a collaborator

 class class1 { function func1($class2) { $class2->func3(); } } $class1 = new class1(); $class2 = new class2(); $class1->func1($class2); 

or enter it through the constructor:

 class class1 { private $class2; public function __construct(Class2 $class2) { $this->class2 = $class2; } function func1() { $this->class2->func3(); } } $class2 = new class2(); $class1 = new class1($class2); $class1->func1(); 
+6
source

I recommend you take a look at static functions / attributes. Basically, you do not need to create an instance of class2, you just need to define the function inside it as static. Take a look at the following implementation:

 <?php class class1 { function func1() { class2::func3(); } function func2() { $this->func1(); } } class class2 { public static function func3() { echo "hello!"; } } $class1 = new class1(); $class1->func1(); ?> 

It is always nice to avoid creating instances of objects as much as possible.

+2
source
 class class1 { function func1() { //Initialize before using it. $class2 = new class2(); $class2->func3(); } function func2() { $this->func1(); } } class class2 { function func3() { echo "hello!"; } } 
0
source

Two things:

Add brackets to the function call and use global to get the variable in scope

 class class1 { function func1() { global $class2; // Get variable into scope $class2->func3(); } function func2() { $this->func1(); } } class class2 { function func3() { echo "hello!"; } } $class1 = new class1(); $class2 = new class2(); $class1->func1(); // Add brackets for function call 
0
source

Source: https://habr.com/ru/post/1437057/


All Articles