I know that php can't nest classes, but it seems that it can if the two classes are in two 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();
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();
}
}
require_once
subclass.php
$var
testvar()
require_once
does not include the code from the other class right on the spot. The behavior of require
, require_once
, include
and include_once
is unique: it "leaves" the current object and "merges" the code from the requested file to the global scope.
This means, that what you perceive as this
class mainclass
{
private $var;
public function __construct()
{
require_once ('subclass.php');
$subinstant = new subclass();
}
}
the PHP interpreter actually sees this (when you create an 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 the comment to this post, it's actually written in the docs:
However, all functions and classes defined in the included file have the global scope.