[英]PHP access class inside another class
所以我有兩個這樣的類:
class foo {
/* code here */
}
$foo = new foo();
class bar {
global $foo;
public function bar () {
echo $foo->something();
}
}
我想在所有方法欄中訪問foo的方法,而不是在bar內的每個方法中聲明它,如下所示:
class bar {
public function bar () {
global $foo;
echo $foo->something();
}
public function barMethod () {
global $foo;
echo $foo->somethingElse();
}
/* etc */
}
我也不想延長它。 我嘗試使用var關鍵字,但似乎沒有用。 我怎么做才能在bar的所有方法中訪問其他類“foo”?
你也可以這樣做:
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. */
}
以后你可以這樣做:
$foo = new foo();
$bar = new bar($foo);
使它成為酒吧的一員。 盡量不要使用全局變量。
class bar {
private $foo;
public function __construct($foo) { $this->foo = $foo; }
public function barMethod() {
echo $this->foo->something();
}
}
簡短的回答:不,沒有辦法實現你想要的。
另一個簡短的回答:你正在以“錯誤的”方式處理課程。 一旦選擇了面向對象的范例 - 忘記“全局”關鍵字。
做你想做的事的正確方法是創建一個foo
實例作為bar
成員並使用它的方法。 這稱為delegation
。
如果你唯一關注的是方法本身而不是另一個類的實例,你可以使用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();
一個選項是自動加載您的課程。 此外,如果您將類設為靜態類,則可以在不使用$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();
}
}
如果將類(foo)轉換為靜態類
//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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.