PHP equivalent of friend or internal

PHPServer Side ProgrammingProgramming

<p>PHP doesn&#39;t support friend-like declarations. It can be simulated in PHP5 using the __get and __set methods and by inspecting a backtrace for the allowed friend classes. But this type of coding practice is considered to be clumsy &minus;</p><pre class="prettyprint notranslate">class sample_friend { &nbsp; &nbsp;private $__friends = array(&#39;My_Friend&#39;, &#39;Other_Friend&#39;); &nbsp; &nbsp;public function __get($key) &nbsp; &nbsp;{ &nbsp; &nbsp; &nbsp; $trace = debug_backtrace(); &nbsp; &nbsp; &nbsp; if(isset($trace[1][&#39;class&#39;]) &amp;&amp; in_array($trace[1][&#39;class&#39;], $this-&gt;__friends)) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return $this-&gt;$key; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; // __get() code goes here &nbsp; &nbsp; &nbsp; trigger_error(&#39;Cannot access private property &#39; . __CLASS__ . &#39;::$&#39; . $key, E_USER_ERROR); &nbsp; &nbsp;} &nbsp; &nbsp;public function __set($key, $value) { &nbsp; &nbsp; &nbsp; $trace = debug_backtrace(); &nbsp; &nbsp; &nbsp; if(isset($trace[1][&#39;class&#39;]) &amp;&amp; in_array($trace[1][&#39;class&#39;], $this-&gt;__friends)) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return $this-&gt;$key = $value; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; // normal __set() code goes here &nbsp; &nbsp; &nbsp; trigger_error(&#39;Cannot access private property &#39; . __CLASS__ . &#39;::$&#39; . $key, E_USER_ERROR); &nbsp; &nbsp;} }</pre>
raja
Updated on 07-Apr-2020 13:09:55

Advertisements