我有一个奇怪的错误,
当我调用$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
?
你说你正处于这个循环中。
最有可能的是,您显示的代码被调用两次,一次是$element
是所需对象,另一次不是——当您使用method_exists()
时,代码会经过该点,如果您不使用它,它就会崩溃。
使用die()
时,循环在第一个元素处终止但这不一定是造成问题的因素。
错误消息
Call to undefined method stdClass::attributes();
支持这一点:注意stdClass
,它应该读Form_Element
。
因此,您需要找出为什么$element
并不总是您想要的对象。
可能您在循环的第一步之后编写了die()
,但在其他步骤中出现了错误。
将die( get_class( $element ) );
更改为print( get_class( $element ).'<br/>' );
,您将看到在哪一行出现错误,并且该行的属性可能为空。