Class not found (in PHP)

This code works without issue:

<?php
namespace NamespaceA;
class A extends \NamespaceB\B {}

namespace NamespaceB;
class B {}

      

But why does the following code cause Fatal error: Class 'NamespaceB \ B' not found in ... file ?

<?php
namespace NamespaceA;
class A extends \NamespaceB\B {}

namespace NamespaceB;
class B extends \NamespaceC\C {}

namespace NamespaceC;
class C {}

      

And this code also works without issue:

<?php
namespace NamespaceA;
class A extends \NamespaceB\B {}

namespace NamespaceC;
class C {}

namespace NamespaceB;
class B extends \NamespaceC\C {}

      

UPD: Without any namespace, also Fatal error: Class 'B' not found in ... file :

<?php

class A extends B {}

class B extends C {}

class C {}

      

Works without problems:

<?php

class A extends B {}

class B {}

      

+3


source to share


2 answers


http://php.net/manual/en/keyword.extends.php

Classes must be defined before using them. If you want class A to extend class B, you first need to define class B. The order in which the classes are defined is important.

Edit:

Found more:

Fatal error while extending an included class



After some research, it became clear that you can actually use the class before you declare it. But the declaration of the class and all parent classes must be in one file.

So, if you declare a parent class in one file and a child class in another, it won't work.

Also, you must first declare parent classes. After that, you can expand them.

Change number 2 :

Ok, so I did some more research on this. There are probably some internal implementation details that currently allow one case to work (my guess would be from auto-loading), however this could change at any time and should never be relied upon.

+1


source


Use include_once () first to add all files to your index file, and when you go to any class, instantiate that parent class first. Example:



index.php-->
<?php
    include_once('parentClass.php');
    include_once('childClass.php');

    $parentObj = new parent();
    $childObj = new child();
?>

child.php-->
<?php
  class child extends parent{
   function __construct(){

    }
  }
?>

      

0


source







All Articles