覆盖非覆盖 $this 引用的 PHP 类方法
所以,我在一些 php OO 方面遇到了麻烦。我认为代码可以最好地解释它:
class foo {
$someprop;
public function __construct($id){
$this->populate($id);
}
private function populate($id){
global $db;
// obviously not the call, but to illustrate the point:
$items = $db->get_from_var1_by_var2(get_class($this),$id);
while(list($k,$v) = each($items)){
$this->setVar($k,$v);
}
}
private function setVar($k,$v){
// filter stuff, like convert JSON to arrays and such.
$this->$k = $v;
}
}
class bar extends foo {
$otherprop;
public function __construct($id){
parent::__construct($id);
}
private function setVar($k,$v){
// different filters than parent.
$this->$k = $v;
}
}
现在,假设我的 foo 表中有 someprop,并且我的 bar 表中有 otherprop,那么当我传入 ID 时,这应该在我的对象上设置变量。
但是,由于某种原因, foo 工作正常,但 bar 没有设置任何内容。
我的假设是它在 $this->setVar() 调用上崩溃了,并且调用了错误的 setVar,但是如果 get_class($this) 正在工作(确实如此),那么 $this 不应该是酒吧,并且根据关联,setVar() 是 $bar 方法吗?
有人看到我遗漏/做错了什么吗?
So, I'm having trouble with some php OO stuff. I think the code will explain it best:
class foo {
$someprop;
public function __construct($id){
$this->populate($id);
}
private function populate($id){
global $db;
// obviously not the call, but to illustrate the point:
$items = $db->get_from_var1_by_var2(get_class($this),$id);
while(list($k,$v) = each($items)){
$this->setVar($k,$v);
}
}
private function setVar($k,$v){
// filter stuff, like convert JSON to arrays and such.
$this->$k = $v;
}
}
class bar extends foo {
$otherprop;
public function __construct($id){
parent::__construct($id);
}
private function setVar($k,$v){
// different filters than parent.
$this->$k = $v;
}
}
Now, assuming my foo table has someprop in it, and my bar table has otherprop in it, this should set the vars on my object when I pass in an ID.
But, for some reason, foo works perfectly, but bar doesn't set anything.
My assumption is that it is falling apart on the $this->setVar() call, and calling the wrong setVar, but if get_class($this) is working (which it is), shouldn't $this be bar, and by association, setVar() be the $bar method?
Anyone see something I'm missing/doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能覆盖子类中的私有方法。私有方法仅对实现类是已知的,甚至子类也不知道。
不过你可以这样做:
You cannot override private methods in subclasses. A private method is known to the implementing class ONLY, not even subclasses.
You CAN do this though: