Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 30th, 2012  |  syntax: None  |  size: 1.37 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Can a class instantiate another class? (PHP)
  2. class first {
  3.     public $a;
  4.  
  5.     function __construct() {
  6.         $this->a = 'a';
  7.     }
  8. }
  9.  
  10. class second {
  11.     //$fst = new first();
  12.     //public showfirst() {
  13.         //$firsta = $this->first->a;
  14.     //  echo "Here is first $a: " . $firsta;
  15.     //}
  16. }
  17.        
  18. class second {
  19.     $fst = new first();
  20.     //public showfirsta() {
  21.     //  $firsta = $this->fst->a;
  22.     //  echo "Here is first $a: " . $firsta;
  23.     //}
  24. }
  25.        
  26. class First {
  27.     public $a;
  28.  
  29.     public function __construct() {
  30.         $this->a = 'a';
  31.     }
  32.  
  33.     public function getA() {
  34.       return $this->a;
  35.     }
  36. }
  37.  
  38.     class Second {
  39.         protected $fst;
  40.         public function __construct() {
  41.           $this->fst = new First();
  42.         }
  43.  
  44.         public function showfirst() {
  45.            $firsta = $this->fst->getA();
  46.            echo "Here is first {$firsta}";
  47.         }
  48.     }
  49.  
  50.     $test = new Second();
  51.     $test->showfirst();
  52.        
  53. $fst = new first();
  54.        
  55. public showfirst() {
  56.        
  57. $firsta = $this->first->a;
  58.        
  59. echo "Here is first $a: " . $firsta;
  60. }
  61.        
  62. class second {
  63.     public function showfirst() {
  64.         $fst = new first();
  65.         $firsta = $fst->a;
  66.         echo "Here is first $a: " . $firsta;
  67.     }
  68. }
  69.        
  70. class second {
  71.  
  72.     public $fst;
  73.  
  74.     public function showfirsta() {
  75.     $this->fst = new first();
  76.     $firsta = $this->fst->a;
  77.     echo "Here is first $a: " . $firsta;
  78.     }
  79. }