van abel van abel - 1 month ago 17
PHP Question

PHP can nest class in two files?

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();


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, and the result is as expected. I just don't understand the
require_once
, it seems that it will include the code in
subclass.php
, so what's the difference, compared to write it directly at the same position?

What's more, how can I access the variable
$var
in
testvar()
? (Use as many methods as you can think), thanks!

Answer

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.