Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a PHP class from within another class

Tags:

oop

php

really simple one I'm guessing but why does the below not work? I'm guessing it's a scope thing where class2 isn't visible from within class1. Yes, I'm getting "Call to member function on a non-object" error.

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 give me a fix for this I'd be very grateful. I've been searching around for a while but I'm getting lots of examples of others trying to instantiate new classes inside other classes and similar and not this particular problem I have.

You'd be right in thinking I don't do a whole lot with classes!

like image 296
Lee Ward Avatar asked Jan 16 '23 10:01

Lee Ward


1 Answers

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

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well […] Within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.

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

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

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

$class1 = new class1();
$class2 = new class2();
$class1->func1($class2);

or inject it via 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();
like image 100
Gordon Avatar answered Jan 18 '23 23:01

Gordon