php - How to Access the private member of class? -


this question has answer here:

xpostmodel object ( [script:model:private] => abc ) 

i wanna change abc efg how can ? there way ?

if can't make changes class definition , there no public setter method class property, , need able directly edit property outside class, option using reflection methods, see example here: https://stackoverflow.com/a/6448613/1362634

here example should work in case set private property $script in $obj of type xpostmodel (where property inherited parent class model):

$obj = new xpostmodel(); $refproperty = new reflectionproperty('model', 'script'); $refproperty->setaccessible(true); $refproperty->setvalue($obj, 'def'); 

and here working code example mockup class definitions simulate situation of question.

<?php error_reporting(-1); ini_set('display_errors', 1);  class model {     private $script = 'abc'; }  class xpostmodel extends model {}  $obj = new xpostmodel();  print_r($obj); // check original value of inherited private property  $refproperty = new reflectionproperty('model', 'script'); $refproperty->setaccessible(true); $refproperty->setvalue($obj, 'def');  print_r($obj); // check property has been changed 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -