Leonardo Leandro
Leonardo Leandro

Reputation: 393

Namespace works for a class, but won't work for others

I am working on a PHP project and I am still learning how to apply namespaces to it. I've come up with the following situation:

File structure is

app.php
index.php
bar.php
sandbox
   \_index.php
   \_Foo.class.php

The contents of the files are as follows:

app.php

<?php
function strtocapital($string)
{  
    return substr(strtolower($string), 0, strrpos($string, '/')) . substr(strtoupper($string), strrpos($string, '/'), 2) . substr(strtolower($string), strrpos($string, '/') + 2);
}

function autoloader($className)
{
    $path = __DIR__ . '/' . strtolower($className) . '.php';

    if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
        $className = str_replace('\\', '/', $className);
        $path = __DIR__ . '/' . strtolower($className) . '.php';
    }

    if (!is_file($path)) {
        $className = strtocapital($className);
        $path = __DIR__ . '/' . $className . '.class.php';
        if (!is_file($path)) {
            return false;
        }
    }

    include_once $path;
    echo "Successfully loaded ${className}<br>";
}

spl_autoload_register("autoloader");

index.php

<?php
require 'app.php';

use Sandbox\Foo as Fuu;

echo __DIR__ . '<br>';

$foo = new Fuu();

try {
    echo $foo::FOOFOO;
    $foo::foofoofoo();
} catch (Exception $e) {
    print_r($e);
}

bar.php

<?php
class Bar
{
    const BARBAR = "dada";

    public static function barbarbar()
    {
        echo "Bar bar bar";
    }
}

sandbox/index.php

<?php
require '../app.php';

use Bar;

echo __DIR__ . '<br>';

$bar = new Bar();

try {
    echo $bar::BARBAR;
    $bar::barbarbar();
} catch (Exception $e) {
    print_r($e);
}

sandbox/Foo.class.php

<?php
class Foo
{
    const FOOFOO = "bla";

    public static function foofoofoo()
    {
        echo "Foo foo foo";
    }
}

Despite the fact I receive both successful messages:

Successfully loaded Sandbox\Foo
Successfully loaded Bar

I only see the outputs for Bar class. The difference between them is that sandbox/index.php returns HTTP Status 200 and index.php returns HTTP Status 500. However, I see no errors, even after trying error_reporting(E_ALL).

Please help me on this, because doing the same steps for both classes and having one working and the other not is driving me nuts.

Thanks in advance.

Upvotes: 0

Views: 148

Answers (1)

Joe Alvini
Joe Alvini

Reputation: 299

By applying namespace at the top of the page that is using the bar or foo namespace it will define the namespace and work. Do this like so:

namespace foo; #Or namespace bar; or whatever your namespace is.

You can apply that on any page that you need to use that namespace on. A good tutorial on this would be https://www.sitepoint.com/php-53-namespaces-basics/.

Upvotes: 1

Related Questions