Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * This file will demonstrate call by reference (rather than call by value - this would create a copy/clone, rather than a reference).
- * - Gerjo Meier
- */
- // Create an object from a class (instance)
- $myChild = new MyChild();
- // Notice how we pass $myChild as an argument(, MyParrent will store a "reference" to $myChild).
- $myParent = new MyParent($myChild);
- // This should echo the value $someString (which has been given some value via the constructor) of MyChild):
- echo $myChild->getSomeString();
- echo $myParent->example();
- // Update $someString: (mind you we do this via $myChild, and not $myParent!)
- $myChild->setSomeString("- I am quite alright!");
- // Both statements should echo the same string $someValue, eventho we only updated $myChild.
- echo $myChild->getSomeString();
- echo $myParent->example(); // Will echo the same value as it contains a reference to $myChild.
- class MyParent {
- private $child;
- public function __construct ($child) {
- // Stores the reference to a "child" object for later use.
- $this->child = $child;
- }
- // Will output the $someString value of the $child class.
- public function example() {
- return $this->child->getSomeString();
- }
- }
- class MyChild {
- private $someString;
- public function __construct () {
- // Assign some default value for this example:
- $this->someString = "How are you doing mate? ";
- }
- // Getter for $someString
- public function getSomeString() {
- return $this->someString . " [via class: " . __CLASS__ . "] <br /> ";
- }
- // Setter for $someString
- public function setSomeString($someString) {
- $this->someString = $someString;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment