Cotten
Cotten

Reputation: 9077

use class from namespace in php in class method

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?

Upvotes: 0

Views: 64

Answers (1)

hek2mgl
hek2mgl

Reputation: 157990

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

Upvotes: 2

Related Questions