0

I'm new to php and trying to use namespaces for the first time and I have this crazy problem in a big php file (simplified below):

B.php:

namespace Logic;

class C {}
class B {}

A.php:

use Logic\C;

class A extends \BaseClass {
    public function __construct() {}
    // [...500 lines of code...]
    private function hi() { $c = new C(); }
}

The hi method gives the error: Class 'Logic\\C' not found in A.php


But if I just reference B in the constructor of A, it works as expected:

class A extends \Base {
    public function __construct() { $dummy = new C(); }
    // [...500 lines of code...]
    private function hi() { $c = new C(); }
}

When the hi method in the modified code above is run, there are no problems.

Can anybody think of a reasonable explanation for why this happens? Am I misusing namespaces in php?

1
  • I have no problem with your code, but you must be sure that B.php is included before using hi() method. Commented Feb 11, 2015 at 12:58

1 Answer 1

2

You need to understand, that the use statement doesn't automatically include the source code file where Logic\C is defined. You need to use an autoloader, or manually require_once that file before accessing classes from that file.


I suggest to follow the manual about namespaces (and the examples there): http://php.net/manual/en/language.namespaces.php

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

1 Comment

There is no need to define alias with the same name as imported class.

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.