0

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.

3
  • Have you tried with absolute paths? Commented Feb 9, 2013 at 15:14
  • Not really I guess. Can you please explain a bit. Commented Feb 9, 2013 at 15:16
  • Occasionally include("$_SERVER[DOCUMENT_ROOT]/lib/whatever.php"); is a good alternative; making the paths absolute, relative to the webserver/vhost base directory. Alternatively consider an autoloader, either with the awful PSR-0 folding, or with a class-path mapping cache. Commented Feb 9, 2013 at 15:18

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.