需要get_object_vars解释

时间:2012-08-21 07:57:47

标签: php

我的一个php教程正在显示波纹管功能。我知道它用于检查属性存在,但我无法得到它的真正含义,我的意思是它的注释行的含义是什么?有人可以向我解释一下吗?

private function has_attribute($attribute) {
            //get_object_vars returns an associative array with all attributes
            //(incl.private ones!) as the keys and their current values as the value
            $object_vars = get_object_vars($this);
            //we don't care about the value, we just want to know if the key exists
            //will return true or false
            return array_key_exists($attribute, $object_vars);
        }

4 个答案:

答案 0 :(得分:4)

查看此示例:

<?php

class someClass
{
    public $someVar1;
    public $someVar2;
}

$cl = new someClass();

$vars = get_object_vars($cl);

print_r($vars);

?>

输出

Array
(
    [someVar1] => 
    [someVar2] => 
)

您的代码的作用是检查您的对象实例是否具有特定属性。

E.g。

$cl->has_attribute("someVar1");

会返回true


参考文献:

答案 1 :(得分:0)

以下是get_object_vars()

的定义
  

数组get_object_vars(object $ object)

     

根据范围获取给定对象的可访问非静态属性。

在这种情况下,它意味着该函数将检查$属性是否已分配给您运行它的类,并返回true或false。

class Foo {
   public $bar = "e";

   private function has_attribute($attribute) {
            $object_vars = get_object_vars($this);
            return array_key_exists($attribute, $object_vars);
   }
}

$foo = new Foo;
$foo->has_attribute('bar'); //true
$foo->has_attribute('fooBar'); //false

答案 2 :(得分:0)

此函数位于一个类中,并返回所有属性(类中的变量)的数组,并返回一个数组,其中键设置为属性名称。

它包含私有属性(这意味着除了对象本身之外通常无法访问它们。

它根本不检查属性值,最后返回一个数组,其中$attribute传递给它truefalse告诉它是否存在或不

答案 3 :(得分:0)

嗯,评论的意思在于解释代码行的作用,并且它们也很好地描述了它们的作用。

<?php

class Foo {
    protected $bar = 'qux';
    public function hasProperty( $name ) {
        return array_key_exists( $name, get_object_vars( $this ) );
    }
}

$foo = new Foo( );
var_dump( $foo->hasProperty( 'does-not-exist' ) ); // false
var_dump( $foo->hasProperty( 'bar' ) ); // true.

请注意,做这样的事情不是“好习惯”;通常,属性是私有的或受保护的原因,您不必确定是否存在某个属性。