【发布时间】:2012-03-23 10:46:01
【问题描述】:
我有这个奇怪的错误,
当我调用$element_attrs = $element -> attributes(); 时,我收到一条通知说属性方法不存在:
Call to undefined method stdClass::attributes();
现在当我在attributes() 调用之前调用die( get_class( $element ) ); 时,php 返回Select_Element,这是正确的!
Form_Element 包含attribute(); 方法。
我很肯定 Select_Element 扩展了 Form_Element 并且这两个文件都被不确定地包含在内。
但是
如果我打电话:
if ( method_exists($element, "attributes") ) {
$element_attrs = $element -> attributes();
}
它有效! method_exists 返回 true,并调用 attributes()!但是当我删除if 命令时,我再次收到错误通知......
这到底是怎么回事!
代码
interface Element{
public function __construct( $element );
public function parse();
}
class Form_Element implements Element{
protected $element;
public function __construct($json_element){
$this -> element = $json_element;
}
public function parse(){
// Removed parsing code, unrelated
}
... removed unrelated methods ...
public function attributes( $key = null, $value = null ){
if ( is_null( $key ) ){
return $this -> element -> attributes;
}
else{
$this -> element -> attributes -> $key = $value;
}
}
}
class Select_Element extends Form_Element implements Element{
public function __construct( $element ) {
parent::__construct( $element );
}
public function parse(){
// Removed parsing code, unrelated
}
}
这是在 Form 类中调用代码的地方:
// 注意:$this -> elements 是 Form_Element 对象的数组
public function edit_form($name_of_element, $name_of_value, $value){
foreach ( $this -> elements as $element ){
if ( method_exists($element, "attributes") ) {
$element_attrs = $element -> attributes();
}
if ( $element_attrs -> name == $name_of_element ){
switch ( $name_of_value ){
case "selected" :
$element -> selected( $value );
break;
case "options" :
$element -> options( $value );
break;
case "value" :
$element -> value( $value );
break;
// add more support as needed
}
}
}
}
有人知道为什么 PHP 认为 attributes(); 不存在吗?即使method_exists($element, "attributes"); 返回true ?
【问题讨论】:
-
您调用该方法的对象是
stdClass(这是反序列化 json 或将数组转换为对象时通常会得到的),因此它显然不是您的Form_Element类的实例. -
@ThiefMaster 但他说
get_class( $element )返回正确的类型。 -
您确定您的
element是Form_Element的实例吗? -
运算符是否有空格?应该是这样的
$element->attributes(); -
@Truth 我认为这里的简单答案是他处于循环中,并且
die()不需要使用导致问题的元素停止循环。我敢打赌没有涉及 PHP 错误。