Gerard-Meier

Gerard

Feb 10th, 2011
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.60 KB | None | 0 0
  1. <?php
  2. /*
  3.  *  This file will demonstrate call by reference (rather than call by value - this would create a copy/clone, rather than a reference).
  4.  *   - Gerjo Meier
  5.  */
  6.  
  7.  // Create an object from a class (instance)
  8. $myChild  = new MyChild();
  9.  
  10. // Notice how we pass $myChild as an argument(, MyParrent will store a "reference" to $myChild).
  11. $myParent = new MyParent($myChild);
  12.  
  13. // This should echo the value $someString (which has been given some value via the constructor) of MyChild):
  14. echo $myChild->getSomeString();
  15. echo $myParent->example();     
  16.  
  17. // Update $someString: (mind you we do this via $myChild, and not $myParent!)
  18. $myChild->setSomeString("- I am quite alright!");
  19.  
  20. // Both statements should echo the same string $someValue, eventho we only updated $myChild.
  21. echo $myChild->getSomeString();
  22. echo $myParent->example(); // Will echo the same value as it contains a reference to $myChild.
  23.  
  24.  
  25.  
  26. class MyParent {
  27.     private $child;
  28.    
  29.     public function __construct ($child) {
  30.         // Stores the reference to a "child" object for later use.
  31.         $this->child = $child;
  32.     }
  33.    
  34.     // Will output the $someString value of the $child class.
  35.     public function example() {
  36.         return $this->child->getSomeString();
  37.     }
  38. }
  39.  
  40. class MyChild {
  41.     private $someString;
  42.  
  43.     public function __construct () {
  44.         // Assign some default value for this example:
  45.         $this->someString = "How are you doing mate? ";
  46.     }
  47.    
  48.     // Getter for $someString
  49.     public function getSomeString() {
  50.         return $this->someString . " [via class: "  . __CLASS__ . "] <br /> ";
  51.     }
  52.    
  53.     // Setter for $someString
  54.     public function setSomeString($someString) {
  55.         $this->someString = $someString;
  56.     }
  57. }
  58.  
  59. ?>
Advertisement
Add Comment
Please, Sign In to add comment