Materno
Materno

Reputation: 353

PHP can not create instance of class with namespace

I've got the following problem:

This is my super basic class:

class A
{
    function foo()
    {
        echo "bar";
    }
}

Now in front of the class declaration I use the following code:

$a = new A();
$a->foo();

When I open the php file in the browser, the output is "bar". Fine!

Now I want to do the same thing in another file.

directly in the first place I declare the following namespace:

namespace model\dbAction;

This is the path where my file with the class above is located.

So in another php file I do the following:

$a = new \model\dbAction\A();
$a->foo();

But I don't get any output and other code after that won't run so it looks like it breaks directly after the instancing of the class.

Any ideas why instancing the class in another file is not working?

Thanks!

Full code first php file:

<?php
namespace model\dbAction;
class A
{
    function foo()
    {
        echo "bar";
    }
}

Full code of the second file (which I call in the browser):

$a = new \model\dbAction\A();
$a->foo();

Upvotes: 0

Views: 2537

Answers (1)

Rob W
Rob W

Reputation: 9142

You still need to include the file -- providing the namespace itself will not include the file for you... unless you're using an autoloader. See: How do I use PHP namespaces with autoload?

Upvotes: 1

Related Questions