Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to pass by reference a class var to a global var in PHP?
    primarykey
    data
    text
    <p>please tell me theres a way around this...</p> <pre><code>$my_var = 'hello'; class Test{ private $my_var; private $my_internal_var = 'if you see this it works!'; function __construct(){ global $my_var; $this-&gt;my_var = &amp;$my_var; } function get_my_var(){ return $this-&gt;my_var; } function set_my_var($value){ $this-&gt;my_var = $value; } function set_my_var_to_internal_reference(){ //this line should make $my_var in root, $my_var in this object, and $my_var in //all external functions point to $my_internal_var. $this-&gt;my_var = &amp;$this-&gt;my_internal_var; } } function get_my_var(){ global $my_var; return $my_var; } function set_my_var($value){ global $my_var; $my_var = $value; } $my_obj = new Test(); echo '&lt;h2&gt;set default starting value&lt;/h2&gt;'; echo 'obj : '.$my_obj-&gt;get_my_var().'&lt;br&gt;'; //echoes 'hello' - this is ok echo 'func: '.get_my_var().'&lt;br&gt;'; //echoes 'hello' - this is ok echo 'root: '.$my_var.'&lt;br&gt;'; //echoes 'hello' - this is ok set_my_var('hello world!'); echo '&lt;h2&gt;set to value by function&lt;/h2&gt;'; echo 'obj : '.$my_obj-&gt;get_my_var().'&lt;br&gt;'; //echoes 'hello world!' - this is ok echo 'func: '.get_my_var().'&lt;br&gt;'; //echoes 'hello world!' - this is ok echo 'root: '.$my_var.'&lt;br&gt;'; //echoes 'hello world!' - this is ok $my_obj-&gt;set_my_var('hello world again!'); echo '&lt;h2&gt;set to value by object method&lt;/h2&gt;'; echo 'obj : '.$my_obj-&gt;get_my_var().'&lt;br&gt;'; //echoes 'hello world again!' - this is ok echo 'func: '.get_my_var().'&lt;br&gt;'; //echoes 'hello world again!' - this is ok echo 'root: '.$my_var.'&lt;br&gt;'; //echoes 'hello world again!' - this is ok $my_obj-&gt;set_my_var_to_internal_reference(); echo '&lt;h2&gt;set to object internal reference&lt;/h2&gt;'; echo 'obj : '.$my_obj-&gt;get_my_var().'&lt;br&gt;'; //echoes ' ' - this is NOT ok. should be 'if you see this it works!' echo 'func: '.get_my_var().'&lt;br&gt;'; //echoes 'hello world again!' - this is NOT ok. should be 'if you see this it works!' echo 'root: '.$my_var.'&lt;br&gt;'; //echoes 'hello world again!' - this is NOT ok. should be 'if you see this it works!' </code></pre> <p>Thanks!!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload