lilHar
lilHar

Reputation: 1866

"class not found" error in PHP with double-slashes (\\)

I'm developing in a system in php that uses namespaces.

I have the following code (summarized, obviously).... a class in one location with directory Foo\Bar\fubar.php

<?php 
namespace Foo\Bar;
class fubar
{...

And I have in my other .php...

<?php
use Foo\Bar;
use Foo\Bar\fubar;

class adventurer{
    $doomChickens = new fubar();
}

Now, when I check my error log, I get...

PHP Fatal Error: Class 'Foo\\Bar\\fubar' not found.

I'm a maintainer, not original author, but in general, I'm the type to use includes & requires rather than namespaces.

What kind of error might cause the double-slashes? Is that likely the source of my issue?

Upvotes: 2

Views: 1729

Answers (1)

Anonymous
Anonymous

Reputation: 12090

That is not an error, it's just how PHP prints it out. As you probably know, there are escape sequences for strings like \n for new line and \t for a tab. Well, \\ is the escape sequence for \.

PHP also interprets invalid escape sequences literally, so Foo\Bar would be just that because \B is not a valid escape sequence.

For reference, the escape sequences are only parsed in double quoted strings, not single quoted ones.


As for solving your actual problem, you need to either explicitly include or require the file with the class or use an autoloader. The most common ones are the PSR-0 and PSR-4 autloaders.

By the way, the use Foo\Bar; line is unnecessary.

The first solution would look like this:

<?php
require 'path/to/other/class.php';

use Foo\Bar\fubar;

class adventurer{
    $doomChickens = new fubar();
}

Upvotes: 2

Related Questions