Kapil Sharma
Kapil Sharma

Reputation: 10417

Classpath equivalent in PHP namespace confusion

A product in my company (& me too) was using PHP 5.2.

I want to switch to 5.4 so I'm doing some basic tests with 5.4 for the first time.

As per PSR 0, I followed the following folder structure for a simple test:

Projectfolder
   |
   + index.php
   |
   + lib
      |
      + vendor
          |
          +  mylib
               |
               + MyClass.php (Having namespace \mylib )

Here is our code, called MyClass.php:

namespace \mylib;
class MyClass {
    public $testA;
    public function MyClass(){
        $this->testA = "test entry";
    }
}

My problem is how to get an instance of MyClass in the index.php file?

Before Namespace, I could have done this:

include "lib/vendor/mylib/MyClass.php";
$myClass = new MyClass();
echo $myClass->testA;

Now with namespace, I try the following code:

<?PHP
use mylib\MyClass
$myClass = new MyClass();
echo $myClass->testA;

However, I get the following error:

Fatal error: Class 'mylib\MyClass' not found ...

My problem is, how do I tell PHP to look namespace files in folder lib\vendor.

In Java, we generally define a classpath. Is there a similar setting in PHP?

As seen in some examples in namespace tutorial, I need to include all PHP files containing all classes to be used (10, 20, 50 any number). I guess that should not be the case or whole purpose of introducing namespace in PHP will be defeated.

Upvotes: 0

Views: 5701

Answers (1)

itsid
itsid

Reputation: 811

even WITH namespaces you must include the files. Namespaces are for referencing those classes AFTER they are included.

SO that you can

include "lib/vendor/mylib/MyClass.php";
use mylib;
\mylib\myClass::myFunction();

without new MyClass();

see http://php.net/manual/en/language.namespaces.php for detailed example

Upvotes: 2

Related Questions