Search code examples
phpclassinheritancenamespacesextend

PHP Namespace Class


I read up quite a bit on namespaces in PHP and I'm still confused.

I have a class in a different folder that is under the namespace Entity (Class A).

I have another class in a different folder that is under the same namespace (Class B), and extends class A.

I get an error saying class A could not be found.

My main question is - do I have to include class A when I create a new instance of class B?

This is my code: (Class A)

 namespace Entity;
    //Framework/Entity/BaseModel.php
    class BaseModel { 

      //TODO: IMPLEMENT THIS
      public function GetList() {
        return null;
      }

    } 

(Class B)

namespace Entity;
//Models/Points.php
class Points extends BaseModel{
    public $Id = null;
}

(Main File)

 require_once(dirname(dirname(__FILE__)) . '/Models/Points.php');
  $points = new Points();

Solution

  • Namespaces have nothing to do with actually including files, those are two completely separate mechanisms. So, yes, you will still have to require_once the file that the class is defined in before you can use it.

    Having said that, especially with namespaces, autoloaders are typically used so you don't have to write a ton of require code. If you organise your class files in folders exactly as their namespaces are, it's very easy to autoload their files. See http://php.net/manual/en/language.oop5.autoload.php and https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md