开发者

in php, is there a way to access properties from child class in parent class

开发者 https://www.devze.com 2023-03-03 09:26 出处:网络
I\'m pretty sure no way but would like to check / confirm. I could pass in props via function but this would require changing a set of functions that I would rather not. I\'m using php 5.3.

I'm pretty sure no way but would like to check / confirm.

I could pass in props via function but this would require changing a set of functions that I would rather not. I'm using php 5.3.

for example:

<?php
class A{
  public function accessProps(){
    echo "about to show props<br />";
    // cant access, child::?
    var_dump($this->props);
   }
}

class B extends A{
   //want this accessible in parent class
   public $props=array('green','blue','red');

   public function sayHello(){
      echo 'hello ';
      var_dump($this->props);
  }
}

$b=new B();
$a=new A();

$b->sayHello();
$a->accessProps();

?>

edit - I like the reflection idea but would be a little hesitant to add reflection for only this one situation. Perhaps easiest / simplest way would just be to pass props in classes that want it and have it as an optional argument in the constuctor. That way, no change to classes that don't need it and access for classes that do need it. I think that should do it. Like this:

开发者_开发知识库
class A{
   public function __construct($props=null){
       if($props){
          $this->props=$props;
       }

   }
}


class B extends A{

   public $props=array('green','blue','red');

    public function __construct(){
        parent::__construct($this->props);
    }


Short Answer YES.

A bit longer answer, the way you are doing it, no.

Detailed answer:

They way you have written it it's not doable because class A has no clue about the child. But if you have a setter in class A then you can use the SPL as so:

class A{
  public function accessProps($child){

    $reflect = new ReflectionClass($child);
    $props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC |  ReflectionProperty::IS_PROTECTED);

   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消