code_junkie

PHP property's scope overridden by passing as reference?

Nov 10th, 2011
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. class foo
  2. {
  3. protected bar = array();
  4. getBar()
  5. {
  6. return &bar;
  7. }
  8.  
  9. }
  10.  
  11. class foo2
  12. {
  13. blip = new foo().getBar(); // i know this isn't php
  14. }
  15.  
  16. <?php
  17. class foo {
  18. protected $bar;
  19.  
  20. public function __construct()
  21. {
  22. $this->bar = array();
  23. }
  24.  
  25. public function &getBar()
  26. {
  27. return $this->bar;
  28. }
  29. }
  30.  
  31. class foo2 {
  32.  
  33. var $barReference;
  34. var $fooInstance;
  35.  
  36. public function __construct()
  37. {
  38. $this->fooInstance = new foo();
  39. $this->barReference = &$this->fooInstance->getBar();
  40. }
  41. }
  42. $testObj = new foo2();
  43. $testObj->barReference[] = 'apple';
  44. $testObj->barReference[] = 'peanut';
  45. ?>
  46. <h1>Reference</h1>
  47. <pre><?php print_r($testObj->barReference) ?></pre>
  48. <h1>Object</h1>
  49. <pre><?php print_r($testObj->fooInstance) ?></pre>
Add Comment
Please, Sign In to add comment