[英]How to include file & access class method from from within a method of another class?
我有一個名為numDisplay
的類, numDisplay
包含幾種方法。 這些方法中的大多數都需要使用另一個稱為prefs
類中的方法,該方法在工作期間包含在另一個文件中。
我想我可以包含文件,實例化類prefs
,然后從需要它的每個方法內部分別訪問該方法,但是,我希望有更好的方法嗎?
我想到了在numDisplay
的__constructor
中執行文件require_once
並在那里實例化該類,然后我可以從numDisplay
的方法中調用它。
我嘗試了以下代碼和各種語法變體,但無法正常工作。 我該怎么辦?
class numDisplay {
private $P;
function __construct($P) {
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/classes/preferences.php');
$P = new Preferences();
}
public function displayBSNo($num, $invType) {
$auto_bs_no = $this->$P->getPreference('auto_bs_no');
$length_bs_no = $this->$P->getPreference('length_bs_no');
$length_alt_bs_no = $this->$P->getPreference('length_alt_bs_no');
if ($invType == 1) { // It's a standard BS
if ($auto_bs_no == '1') {
return "BS-" . $this->pad($num, $length_bs_no);
} else {
if ($num == '') {
return '<i>none</i>';
} else {
return $num;
}
}
}
elseif ($invType == 2) {
return "PI-" . $this->pad($num, $length_alt_bs_no);
}
}
}
當我嘗試使用displayBSNo()時,出現以下錯誤:
Fatal error: Call to a member function getPreference() on a non-object in /home/peter/Documents/websites/Our_websites/bookkeeper.ph/books.bookkeeper.ph/public/includes/classes/common.classes.php on line 347
代替
$this->$P->getPreference('')
采用
$this->P->getPreference('')
您沒有在構造函數中設置屬性:
function __construct($P) {
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/classes/preferences.php');
$P = new Preferences();
}
在這里, $P
只是構造函數范圍內的局部變量。 要將值存儲在屬性P
,您應該具有:
$this->P = new Preferences();
在其余的代碼中:
$this->$P->getPreference(...)
引用名稱保留在$P
的屬性,這可能不是您想要的。 它應該是:
$this->P->getPreference(...)
當您犯此類錯誤時,PHP實際上會發出通知。 您可以通過以下方式看到它們:
error_reporting(-1);
ini_set('display_errors', 'On');
僅在開發期間使用這些設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.