【问题标题】:Yii2: How to get attributes of $this?Yii2: 如何获取 $this 的属性?
【发布时间】:2021-02-01 21:26:48
【问题描述】:

我有一个模型类 A 和一个子类 B。

class A extends \yii\base\Model {
    public $a1,$a2;
}

class B extends A {
    public $b1,$b2;
}

$o = new B();

如何将$o 的属性值作为数组获取,但仅来自class B,而不是来自class A

当调用$o->attributes 我得到['a1'=>..., 'a2'=>...,'b1'=>..., 'b2'=>...]

我的预期结果是['b1'=>..., 'b2'=>...]

是否有 Yii2 的做法,或者我们是否必须使用一些 PHP 函数/语言特性?

【问题讨论】:

标签: php yii2


【解决方案1】:

如果您知道要获取哪些属性,可以在 yii\base\Model::getAttributes() 方法的第一个参数中命名它们,如下所示:

$attributes = $o->getAttributes(['b1', 'b2']);

如果您需要所有属性但不知道那里有哪些属性,您可以使用父类的yii\base\Model::attributes() 方法获取您不想要的属性列表并将其作为getAttributes() 方法的第二个参数传递把它们排除在外。

$except = A::instance()->attributes();
$attributes = $o->getAttributes(null, $except);

【讨论】:

    【解决方案2】:

    您可以使用反射来枚举与您想要的类匹配的属性。 https://www.php.net/manual/en/reflectionclass.getproperties.php

    class A extends \yii\base\Model {
        public $a1,$a2;
    }
    
    class B extends A {
        public $b1,$b2;
    }
    
    $o = new B();
    
    $ref = new \ReflectionClass(B::class);  
    $props = array_filter(array_map(function($property) {
        return $property->class == B::class ? $property->name : false; 
    }, $ref->getProperties(\ReflectionProperty::IS_PUBLIC)));
    
    print_r($props);
    
    /*
    Will Print
    Array
    (
        [0] => b1
        [1] => b2
    )
    */
    

    【讨论】:

      【解决方案3】:

      你可以在类Bconstruct中取消设置变量$a1$a2

      ...
      class B extends A{
        public $b1, $b2;
        
        public function __construct(){
          unset($this->a1, $this->a2);
        }
      }
      ...
      

      就我而言,当我查看$o->attributes 时。 a1a2 属性仍然存在。

      但是变量值变成*uninitialized* 并且不能使用($o->a1 将引发并显示错误消息)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多