PHP - Get Classes public variables?
Please consider the code below.
class A {
public function __construct() {
}
}
class B extends A {
public $a = "a";
public $b = "b";
public $c = "c";
}
How do I get the class B's public variables f开发者_如何学Pythonrom within the parent class without knowing precisely what they are?
class A {
public $d;
public function __construct() {
$reflect = new ReflectionClass($this);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
var_dump($props);
}
}
class B extends A {
public $a = "a";
private $b = "b";
public $c = "c";
}
new B();
Output (notice no 'b', but A's public 'd' is in there, with a mention it's declared in A):
array(3) {
[0]=>
&object(ReflectionProperty)#3 (2) {
["name"]=>
string(1) "a"
["class"]=>
string(1) "B"
}
[1]=>
&object(ReflectionProperty)#4 (2) {
["name"]=>
string(1) "c"
["class"]=>
string(1) "B"
}
[2]=>
&object(ReflectionProperty)#5 (2) {
["name"]=>
string(1) "d"
["class"]=>
string(1) "A"
}
}
In A create an instance of B and then use
http://www.php.net/manual/en/reflectionclass.getproperties.php
Anyways, what are you trying to do ?
class A {
public function __construct() {
$array = get_class_vars('B'); // public vars of class B
}
}
class B extends A {
public $a = "a";
public $b = "b";
public $c = "c";
}
Inject the the B-Class-Object into the A-Class-Object:
class A {
public $b;
public function __construct(B $b_object) {
$this->b = $b;
}
}
class B {
public $a = "a";
public $b = "b";
public $c = "c";
}
So the constructor waits for a Objekt of B here. And now let's use it.
$b = new B();
$a = new A($b);
$a->b->a;
$a->b->b;
$a->b->c
EDIT: Sorry, I didn't see that class B extends class A. So just forget about my solution :)
A subclass inherits from the superclass. Just as a father doesn't inherit any genes from his daughter, only gives them, this isn't possible. Well, technically it is, but it isn't the correct way of implementing object-oriented behavior.
I recommend giving the variable to the superclass, that way it is accessible by both classes, although I'm unsure what you're using it for.
Hope that helps!
精彩评论