Yii2:如何获取 $this 的属性?
Yii2: How to get attributes of $this?
我有一个模型 class A 和一个子class 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 functions/language 功能?
您可以在 class B
construct
中取消设置变量 $a1
和 $a2
...
class B extends A{
public $b1, $b2;
public function __construct(){
unset($this->a1, $this->a2);
}
}
...
就我而言,当我查找 $o->attributes
时。属性 a1
和 a2
仍然存在。
但变量值变为 *uninitialized*
且无法使用($o->a1
将引发并显示错误消息)。
您可以使用反射来枚举与您想要的 class 匹配的属性。
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
)
*/
如果你知道你想要得到什么属性,你可以在 yii\base\Model::getAttributes()
方法的第一个参数中命名它们,如下所示:
$attributes = $o->getAttributes(['b1', 'b2']);
如果你需要所有属性但不知道有哪些属性,你可以使用父class的yii\base\Model::attributes()
方法来获取你不需要的属性列表并传递它作为 getAttributes()
方法的第二个参数将它们排除在外。
$except = A::instance()->attributes();
$attributes = $o->getAttributes(null, $except);
我有一个模型 class A 和一个子class 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 functions/language 功能?
您可以在 class B
construct
$a1
和 $a2
...
class B extends A{
public $b1, $b2;
public function __construct(){
unset($this->a1, $this->a2);
}
}
...
就我而言,当我查找 $o->attributes
时。属性 a1
和 a2
仍然存在。
但变量值变为 *uninitialized*
且无法使用($o->a1
将引发并显示错误消息)。
您可以使用反射来枚举与您想要的 class 匹配的属性。 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
)
*/
如果你知道你想要得到什么属性,你可以在 yii\base\Model::getAttributes()
方法的第一个参数中命名它们,如下所示:
$attributes = $o->getAttributes(['b1', 'b2']);
如果你需要所有属性但不知道有哪些属性,你可以使用父class的yii\base\Model::attributes()
方法来获取你不需要的属性列表并传递它作为 getAttributes()
方法的第二个参数将它们排除在外。
$except = A::instance()->attributes();
$attributes = $o->getAttributes(null, $except);