Require another file in php class objects

Suppose I have the following code:

a.php

<?

class H{

    public $i = 123;

    public function S(){
        require "b.php";
        die;
    }
}

$i = new H();
$i -> S();

b.php

<?

echo $i->i;

However, system throws an error in file b.php that variable i is not defined.

How can I fix this problem?

If it's possible, could someone kindly tell me why this is happening?

Answer

Solution:

You should never include a file like that in case of OOP. As oop and procedural PHP is different. Whenever you want to echo anything inside the class you should use $this keyword that signifies that you are working in context of current class object. So thats why your code is not working and you are getting that variable i is not defined. As nathanael said its not an elegant way of coding

Answer

Solution:

you can write in b.php

echo $this->i;

and that would work, but that is not an elegant way of coding,

alternatively you can make $i accessible in S() in a.php you would have

public function S(){
    global $i;
    require "b.php";
    die;
}

And that would work also, but is no more elegant

when you require b.php in the method S(), it will inject the code from b.php inside the method S(), and there is no variable $i

you have a global variable $i, which is not accessible from S() unless you explicitly make it accessible

Source