方法存在,但PHP说它没有

Joe*_*984 1 php methods codeigniter function

我不知道为什么会这样,但也许有人在这里知道.我遇到了PHP method_exists()函数的问题.我传入一个对象和方法名称作为字符串,如下所示:

method_exists($question, "id")
Run Code Online (Sandbox Code Playgroud)

我对它做了一个var_dump,它说它返回false

echo var_dump(method_exists($question, "id")); // returns bool(false)
Run Code Online (Sandbox Code Playgroud)

但这是一个奇怪的部分.我用以下内容替换该行:

echo $question->id; // returns the id number
Run Code Online (Sandbox Code Playgroud)

那么如果对象方法有效,它怎么能返回false?

我在对象上做了一个var_dump,所以你可以看一看

object(stdClass)#19 (11) { 
  ["id"]=> string(1) "4" 
  ["question"]=> string(67) "This is a question?" 
  ["answer_id"]=> string(1) "0" 
  ["status"]=> string(6) "active"
  ["author_id"]=> string(1) "1" 
  ["created_on"]=> string(10) "1323221575" 
  ["last_edited"]=> string(10) "1324335140" 
  ["order"]=> string(6) "random" 
  ["answer_position"]=> string(1) "1" 
  ["first_name"]=> string(3) "Joe" 
  ["last_name"]=> string(8) "McMurray" }
Run Code Online (Sandbox Code Playgroud)

你可以马上看到第一个名为"id"的.那为什么它会返回假?

谢谢

lon*_*day 7

这不是一种方法:它是一种财产.试试property_exists:

echo var_dump(property_exists($question, "id")); // returns bool(true)
Run Code Online (Sandbox Code Playgroud)

方法只是定义为类的一部分的函数,例如:

public function someMethod($someParam) {...
Run Code Online (Sandbox Code Playgroud)

属性是在对象上设置的有效变量,例如:

public $id = 0;
Run Code Online (Sandbox Code Playgroud)