php中如何访问私有变量?
我尝试了网上可用的所有技巧,但不知道为什么,我无法访问该变量..这是包含私有变量的类的片段:
class PANASONIC_PRICESHEET {
public $models = array();
public $options = array();
public $accessories = array();
private $identifier = '';
private $name = '';
private $currency1 = '€';
private $currency2 = '£';
/**
*
*/
public function __construct($name1 = 'unnamed', $identifier1 = '') {
$this->name = $name1;
$this->identifier = $identifier1;
}
public function getIdentifier() {
return $this->identifier;
}
/**
*
*/
public function getName($withIdentifier = false) {
if ($withIdentifier) {
return $this->name . " - " . $this->identifier;
} else {
return $this->name;
}
}
}
这是我访问它的方式:
$thisName = $pricesheet->getName();
$thisIdentifier = $pricesheet->getIdentifier();
我收到此错误:
Fatal error: Cannot access private property PANASONIC_PRICESHEET::$name in
C:\AppServ\www\dashboard\sites\all\modules\_custom\pricing_system\pricing_system.inc
on line 316
如何解决这个问题?我无法将该字段公开,它根本不是一个选项。有什么建议请。
编辑 - 1
问题已解决: 我本来应该打电话 $_pricesheet->getName(); 非常感谢您的建议。
I tried all the tricks available in the net, but dont know why, i am not able to access the variable.. heres the snippet of class containing private variable:
class PANASONIC_PRICESHEET {
public $models = array();
public $options = array();
public $accessories = array();
private $identifier = '';
private $name = '';
private $currency1 = '€';
private $currency2 = '£';
/**
*
*/
public function __construct($name1 = 'unnamed', $identifier1 = '') {
$this->name = $name1;
$this->identifier = $identifier1;
}
public function getIdentifier() {
return $this->identifier;
}
/**
*
*/
public function getName($withIdentifier = false) {
if ($withIdentifier) {
return $this->name . " - " . $this->identifier;
} else {
return $this->name;
}
}
}
And here is how i am accessing it:
$thisName = $pricesheet->getName();
$thisIdentifier = $pricesheet->getIdentifier();
And I am getting this error:
Fatal error: Cannot access private property PANASONIC_PRICESHEET::$name in
C:\AppServ\www\dashboard\sites\all\modules\_custom\pricing_system\pricing_system.inc
on line 316
How to fix this? I cannot make the field PUBLIC, its not a option at all. Any suggestions please.
EDIT - 1
Issue has been solved:
I was suppose to call $_pricesheet->getName();
thanks a lot for suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
目前这对我有用。请查看此处。您可能正在尝试访问
$pricesheet->name;
This is currently working for me. Take a look here. You must be probably trying to access
$pricesheet->name;
您可以尝试在公共函数中调用私有函数,该函数返回私有变量。
类似于 Javascript 中的闭包。
希望它有效
You can try to call a private Function in your Public function which returns the private Variable.
Similar to Closures in Javascript.
Hope it works