簡體   English   中英

PHP在父級中訪問子級的私有屬性

[英]PHP Accessing a child's private properties in parent

我有一個父對象,我在我的應用程序中用於一般CRUD - 它有基本的保存和檢索方法,所以我不必將它們重新包含在我的所有對象中。 我的大多數子對象都擴展了這個基礎對象。 這工作正常,但我發現檢索序列化子對象時出現問題。 我在創建子實例的父對象中使用“retrieve”方法,然后從未序列化的子元素的屬性中填充自己 - 這意味着可以“自我反序列化”對象。

唯一的問題是 - 如果子對象具有受保護或私有屬性,則父對象無法讀取它,因此在檢索期間不會被拾取。

所以我正在尋找一種更好的方法來“自我反序列化”或者一種允許父對象“看到”受保護屬性的方法 - 但只是在檢索過程中。

代碼示例:

BaseObject {

 protected $someparentProperty;

 public function retrieve() {

  $serialized = file_get_contents(SOME_FILENAME);
  $temp = unserialize($serialized);
  foreach($temp as $propertyName => $propertyValue) {
    $this->$propertyName = $propertyValue;
  }     

 }

 public function save() {

    file_put_contents(SOME_FILENAME, serialize($this));
 }
}

class ChildObject extends BaseObject {

 private $unretrievableProperty;  

 public setProp($val) {
    $this->unretrivableProperty = $val;
 }
}

$tester = new ChildObject();
$tester->setProp("test");
$tester->save();

$cleanTester = new ChildObject();
$cleanTester->retrieve();
// $cleanTester->unretrievableProperty will not be set

編輯:應該說“私人”不受保護的兒童財產。

試試這樣:

abstract class ParentClass
{
  protected abstract function GetChildProperty();

  public function main()
  {
    $value = $this->GetChildProperty();
  }
}

class ChildClass extends ParentClass
{
  private $priv_prop = "somevalue";

  protected function GetChildProperty()
  {
    return $this->priv_prop;
  }
}

解決此問題的最佳答案是使用反射

例:

$_SESSION[''] = ''; // init

class Base {
    public function set_proxy(){
        $reflectionClass = new ReflectionClass($this);
        $ar = $reflectionClass->getDefaultProperties();

        !isset($ar['host'])  or  $_SESSION['host'] = $ar['host'];
    }
}

class Son1 extends Base {
    private $host = '2.2.2.2';
}

class Son2 extends Son1 {

}


$son1 = new Son1();
$son1->set_proxy(); 
var_dump($_SESSION); // array(2) { [""]=> string(0) "" ["host"]=> string(7) "2.2.2.2" }

unset($_SESSION);
$_SESSION[''] = ''; // init

$son2 = new Son2();
$son2->set_proxy(); 
var_dump($_SESSION); //  array(1) { [""]=> string(0) "" }

如何在子對象中返回$ this-> unretrievableProperty的getProperty()函數

似乎相同的類可見性策略不適用於iherited / parent類。 php文檔沒有解決這個問題。

我建議您將retrieve方法聲明為static,並通過靜態調用而不是當前的“self unserialize”方法獲取$ cleanTester。

static function retrieve() {
  $serialized = file_get_contents(SOME_FILENAME);
  return unserialize($serialized);
}

[...]

$cleanTester = BaseObject::retrieve();

或者您可以使用__get()方法來訪問不可訪問的屬性...我相信這可以添加到BaseObject類並從子類中獲取受保護的屬性。 由於相同的類可見性策略應該應用於BaseObject您可以將__get()方法定義為private或protected。

BaseObject {
  private function __get($propertyName) {
    if(property_exists($this,$propertyName))
      return $this->{$propertyName};

    return null;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM