PHP access class inside another class

So, I have two classes:

class foo { /* code here */ } $foo = new foo(); class bar { global $foo; public function bar () { echo $foo->something(); } } 

I want to access the foo methods inside all method panels without declaring them in each method inside the panel, for example:

 class bar { public function bar () { global $foo; echo $foo->something(); } public function barMethod () { global $foo; echo $foo->somethingElse(); } /* etc */ } 

I do not want to expand it. I tried using the var keyword, but it didn't seem to work. What should I do to access another "foo" class in all bar methods?

+6
variables php global
source share
5 answers

You can do this too:

 class bar { private $foo = null; function __construct($foo_instance) { $this->foo = $foo_instance; } public function bar () { echo $this->foo->something(); } public function barMethod () { echo $this->foo->somethingElse(); } /* etc, etc. */ } 

Later you could do:

 $foo = new foo(); $bar = new bar($foo); 
+7
source share

Make him a member of the bar. Try to never use global variables.

 class bar { private $foo; public function __construct($foo) { $this->foo = $foo; } public function barMethod() { echo $this->foo->something(); } } 
+4
source share

Short answer: no, there is no way to implement what you want.

One more short answer: you work with classes "incorrectly". Once you have chosen the object-oriented paradigm - forget about the "global" keyword.

The right way to do what you want is to instantiate foo as a member of bar and use its methods. This is called delegation .

+2
source share

And if your only focus is on the methods themselves, and not an instance of another class, you can use x extends y .

 class foo { function fooMethod(){ echo 'i am foo'; } } class bar extends foo { function barMethod(){ echo 'i am bar'; } } $instance = new bar; $instance->fooMethod(); 
+1
source share

Option - autoload your classes. Also, if you make your class a static class, you can call it without $classname = new classname() :

 //Autoloader spl_autoload_register(function ($class) { $classDir = '/_class/'; $classExt = '.php'; include $_SERVER['DOCUMENT_ROOT'] . $classDir . $class . $classExt; }); //Your code class bar { private static $foo = null; //to store the class instance public function __construct(){ self::$foo = new foo(); //stores an instance of Foo into the class' property } public function bar () { echo self::$foo->something(); } } 

If you convert your class (foo) to a static class

 //Autoloader spl_autoload_register(function ($class) { $classDir = '/_class/'; $classExt = '.php'; include $_SERVER['DOCUMENT_ROOT'] . $classDir . $class . $classExt; }); //Your code class bar { public function bar () { echo foo::something(); } } 
0
source share

All Articles