php中如何在外部修改類的私人或受保護屬性值

來源:互聯網
上載者:User
php中怎麼在外部修改類的私人或受保護屬性值

在做單元測試架構時,發現了個比較鬱悶的問題:測試人員需要在類外修改類的private或protected成員變數的值,而這些變數沒有抽象成public的屬性,同時為了代碼量的問題,也不可能修改要測試的類。怎麼在類外修改類的私人變數呢?請看下面的關鍵代碼:

類檔案sellAction.php, 內容如下:

cUid;echo "
";echo "output private id :".$this->id;echo "
";echo "output public pId:".$this->pId;echo "
";}}

測試檔案test.php,內容如下:

 $val)        {            $pro = $reflectCls->getProperty($key);if($pro && ($pro->isPrivate() || $pro->isProtected())){$pro->setAccessible(true);$pro->setValue($reference, $val);}else{$reference->$key = $val;}        }        return true;}$act = new SellAction();echo "not set private protect public var";echo "
";var_dump($act);$act->output();$attr = array('cUid'=>'234556', 'pId'=>'987676757', 'id'=> '782100');initReferenceAttr($act, $attr);echo "
";print_r($attr);echo "
";echo "
";echo "set private protect public var ";echo "
";var_dump($act);echo "
";$act->output();

在瀏覽器中,直接瀏覽test.php,內容大致如下:

not set private protect public varobject(SellAction)#1 (3) { ["cUid":protected]=> NULL ["id":"SellAction":private]=> NULL ["pId"]=> NULL } output protected cUid :output private id :output public pId:Array ( [cUid] => 234556 [pId] => 987676757 [id] => 782100 ) set private protect public var object(SellAction)#1 (3) { ["cUid":protected]=> string(6) "234556" ["id":"SellAction":private]=> string(6) "782100" ["pId"]=> string(9) "987676757" } output protected cUid :234556output private id :782100output public pId:987676757

上面的demo主要是通過反射實現該功能。反射功能需要php版本>=5.3,反射的相關資訊請參閱:http://php.net/manual/en/book.reflection.php

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.