简体   繁体   English

Yii2:如何获取 $this 的属性?

[英]Yii2: How to get attributes of $this?

I have a Model class A and a subclass B.我有一个 Model class A 和一个子类 B。

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

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

$o = new B();

How do I get attribute values of $o as Array, but just from class B , not from class A ?如何获取$o的属性值作为数组,但仅来自class B ,而不是来自class A

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

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

Is there an Yii2-way of doing or do we have to fallback on some PHP functions/language features?是否有 Yii2 的做法,或者我们是否必须退回某些 PHP 功能/语言功能?

You can use Reflection to enumerate the properties that match the class you want.您可以使用反射来枚举与您想要的 class 匹配的属性。 https://www.php.net/manual/en/reflectionclass.getproperties.php 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
)
*/

If you know what attributes you want to get you can name them in first param of yii\base\Model::getAttributes() method like this:如果您知道要获取哪些属性,可以在yii\base\Model::getAttributes()方法的第一个参数中命名它们,如下所示:

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

If you need all attributes but don't know what attributes are there, you can use yii\base\Model::attributes() method of the parent class to get list of attributes you don't want and pass it as second argument of getAttributes() method to leave them out.如果您需要所有属性但不知道那里有哪些属性,您可以使用父 class 的 yii yii\base\Model::attributes()方法来获取您不想要的属性列表并将其作为第二个参数传递getAttributes()方法将它们排除在外。

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

You can unset variable $a1 and $a2 in class B construct您可以在 class B construct中取消设置变量$a1$a2

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

In my case, when I look up on $o->attributes .就我而言,当我查看$o->attributes时。 attribute a1 and a2 still exist.属性a1a2仍然存在。

But the variables value become *uninitialized* and can't used ( $o->a1 will raise and showed error message).但是变量值变为*uninitialized*并且不能使用( $o->a1将引发并显示错误消息)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM