PHP namespace confusion

Hi
I am new to PHP and am struggling with namespaces
I have one class declared as

<?php

namespace CodingStandard;

class Manager {

}

and another as

<?php

namespace CodingStandard\Sniffs\Classes;

class Sniff {
	public function f() {
		$xx = new Manager();
	}
}

$x = new Sniff();
$x->f();

This results in the error

PHP Fatal error: Class 'CodingStandard\Sniffs\Classes\CodingStandard\Manager' not found in /root/testPHP/Sniff.php on line 7

How can I reference the Manager class from within the Sniff class?

Thanks

Either use the full-qualified name, i.e $xx = new CodingStandard\Manager(); or add use statement below namespace

namespace CodingStandard\Sniffs\Classes;

use CodingStandard;

class Sniff {
	public function f() {
		$xx = new Manager();
	}
}
2 Likes

The first thing you need to do is to tell your sniffer where to find the manager class. The easiest way to get started is with a simple require statement. So:

namespace CodingStandard\Sniffs\Classes;
require 'Manager.php';
use CodingStandard\Manager;

class Sniff {

    public function f() {
         // Either approach will work
        $xx = new \CodingStandard\Manager();
        $yy = new Manager();
    }
}
$x = new Sniff();
$x->f();

As you might imagine, using require statements can quickly get out of hand as the number of classes increases. When that happens, do some research on autoloaders.

you should load autoload file at the start point of file or require file

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.