PHP access class inside another class

女生的网名这么多〃 提交于 2019-12-01 04:10:53
Sarfraz

You could do like 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);

Make it a member of bar. Try to never use globals.

class bar {
    private $foo;

    public function __construct($foo) { $this->foo = $foo; }

    public function barMethod() {
        echo $this->foo->something();
    }
}

The short answer: nope, there is no way to implement what you want.

Another short answer: you're working with classes in "wrong" way. Once you selected Object Oriented paradigm - forget about "global" keyword.

The proper way of doing what you want is to create an instance of foo as member of bar and use it's methods. This is called delegation.

And if your only focus is the methods themselves as opposed to the 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();

An option is to 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) into 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();
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!