I have a class called numDisplay
containing several methods. Most of those methods need to use a method from another class called prefs
which is contained in another file during the course of their duties.
I think I could include the file, instantiate the class prefs
and then access the method individually from inside each of the methods where it is needed, however, I expect there is a better way?
I thought of doing the file require_once
in the __constructor
of numDisplay
and instantiate the class there also, then I could just call it from the methods of numDisplay
.
I tried the code below and various syntax variations, but can't get it to work. How should I do this please?
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);
}
}
}
When I attempt to use displayBSNo(), I get the following error:
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
Instead of
$this->$P->getPreference('')
use
$this->P->getPreference('')
You're not setting the property in the constructor:
function __construct($P) {
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/classes/preferences.php');
$P = new Preferences();
}
Here, $P
is just a local variable in the scope of your constructor; to store the value inside the property P
, you should have:
$this->P = new Preferences();
In the rest of your code:
$this->$P->getPreference(...)
References the property of which the name is held in $P
, which is probably not what you want. It should be:
$this->P->getPreference(...)
PHP actually emits notices when you make these kinds of mistakes; you can see them with this:
error_reporting(-1);
ini_set('display_errors', 'On');
Use these settings during development only.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.