PHP can nest class in two files? -


i know php can't nest classes, seems can if 2 classes in 2 files:

mainclass.php:

<?php ini_set('display_errors', 'on'); error_reporting(e_all | e_strict);  class mainclass {   private $var;   public function __construct()   {     require_once ('subclass.php');     $subinstant = new subclass();   } } $maininstant = new mainclass(); 

and subclass.php

<?php ini_set("display_errors", "on"); error_reporting(e_all | e_strict); class subclass {   public function __construct()   {     $this->var="this-var\n";     echo $this->var;     $test="test in construct\n";     echo $test;     function testvar()     {       //$this->var = "this-var in fun\n";       //echo $this->var;       $funtest="test in fun\n";       echo $funtest;     }     testvar();   } } 

no errors output, , result expected. don't understand require_once, seems include code in subclass.php, what's difference, compared write directly @ same position?

what's more, how can access variable $var in testvar()? (use many methods can think), thanks!

require_once not include code other class right on spot. behavior of require, require_once, include , include_once unique: "leaves" current object , "merges" code requested file global scope.

this means, perceive this

class mainclass {   private $var;   public function __construct()   {     require_once ('subclass.php');     $subinstant = new subclass();   } } 

the php interpreter sees (when create instance of mainclass):

class mainclass {   private $var;   public function __construct()   {     $subinstant = new subclass();   } }  class subclass {   public function __construct()   {     $this->var="this-var\n";     echo $this->var;     $test="test in construct\n";     echo $test;     function testvar()     {       //$this->var = "this-var in fun\n";       //echo $this->var;       $funtest="test in fun\n";       echo $funtest;     }     testvar();   } } $maininstant = new mainclass(); 

as @federkun pointed in comment post, it's written in docs:

however, functions , classes defined in included file have global scope.


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -