Advertisement
Luxian

PHP inheritance

Jul 19th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.07 KB | None | 0 0
  1. <?php
  2.  
  3. class Base
  4. {
  5.     public function testBase()
  6.     {
  7.         //var_dump(__METHOD__ . ' is ran from: ' . get_class($this));
  8.         return $this->x;
  9.     }
  10. }
  11.  
  12. class Aclass extends Base
  13. {
  14.     private $x = __CLASS__;
  15.     protected $y = __CLASS__;
  16.  
  17.     public function test()
  18.     {
  19.         echo "\tget_class(\$this): "  . get_class($this) . PHP_EOL;
  20.         echo "\tget_class():" . get_class() . PHP_EOL;
  21.         echo "\tmethod: " . __METHOD__ . PHP_EOL;
  22.         echo "\t\$this->x: " . $this->x . PHP_EOL;
  23.         echo "\t\$this->y: " . $this->y . PHP_EOL;
  24.  
  25.         // return static::$x; // Fatal error: Cannot access private property Bclass::$x
  26.         return $this->x;
  27.     }
  28. }
  29.  
  30. class Bclass extends Aclass
  31. {
  32.     private $x = __CLASS__;
  33.     protected $y = __CLASS__;
  34. }
  35.  
  36.  
  37. $bObj = new Bclass();
  38. echo '$bObj = new Bclass();' . PHP_EOL;
  39. echo 'get_class($bObj) => ' . get_class($bObj) . PHP_EOL;
  40. echo '$bObj->test()' . PHP_EOL;
  41. $bObj->test();
  42.  
  43. echo PHP_EOL;
  44. echo '\\Closure::bind(function() { return $this->test(); }, new Aclass(), $bObj)->__invoke()' . PHP_EOL;
  45. \Closure::bind(function() { return $this->test(); }, new Aclass(), $bObj)->__invoke();
  46.  
  47. echo PHP_EOL;
  48.  
  49. echo '\Closure::bind(function() { return $this->test(); }, $bObj, $bObj)->__invoke()' . PHP_EOL;
  50. \Closure::bind(function() { return $this->test(); }, $bObj, $bObj)->__invoke();
  51.  
  52. echo PHP_EOL;
  53.  
  54. // PHP Fatal error:  Uncaught Error: Cannot access private property Aclass::$x
  55. // $aObj = new Aclass();
  56. // $aObj->testBase();
  57.  
  58. /**
  59. OUTPUT:
  60.  
  61. $bObj = new Bclass();
  62. get_class($bObj) => Bclass
  63. $bObj->test()
  64.     get_class($this): Bclass
  65.     get_class():Aclass
  66.     method: Aclass::test
  67.     $this->x: Aclass
  68.     $this->y: Bclass
  69.  
  70. \Closure::bind(function() { return $this->test(); }, new Aclass(), $bObj)->__invoke()
  71.     get_class($this): Aclass
  72.     get_class():Aclass
  73.     method: Aclass::test
  74.     $this->x: Aclass
  75.     $this->y: Aclass
  76.  
  77. \Closure::bind(function() { return $this->test(); }, $bObj, $bObj)->__invoke()
  78.     get_class($this): Bclass
  79.     get_class():Aclass
  80.     method: Aclass::test
  81.     $this->x: Aclass
  82.     $this->y: Bclass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement