WeSee
WeSee

Reputation: 3772

Yii2: How to get attributes of $this?

I have a Model class A and a subclass 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?

When calling $o->attributes I get ['a1'=>..., 'a2'=>...,'b1'=>..., 'b2'=>...]

My expected result is ['b1'=>..., 'b2'=>...].

Is there an Yii2-way of doing or do we have to fallback on some PHP functions/language features?

Upvotes: 0

Views: 1460

Answers (3)

Michal Hynčica
Michal Hynčica

Reputation: 6144

If you know what attributes you want to get you can name them in first param of yii\base\Model::getAttributes() method like this:

$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.

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

Upvotes: 1

Alex
Alex

Reputation: 2122

You can use Reflection to enumerate the properties that match the class you want. 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
)
*/

Upvotes: 2

Hanief Han
Hanief Han

Reputation: 160

You can unset variable $a1 and $a2 in class B construct

...
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. attribute a1 and a2 still exist.

But the variables value become *uninitialized* and can't used ($o->a1 will raise and showed error message).

Upvotes: 0

Related Questions