Undefined type 'Fromtify\Database\R'

249 views Asked by At

I'm new to PHP. When working with namespaces, I ran into a problem with RedBeanPHP.
I have php script "db.php":


namespace Fromtify\Database {

    require_once('../libs/rb-mysql.php');

    class Contoller
    {
        public function Connect()
        {
            R::setup(
                #My database settings here...
            );

            if (!R::testConnection()) {
                echo 'Cant connect to database';
                exit;
            }
        }
    }
}

My IDE(VSCode) tells me: "Undefined type 'Fromtify\Database\R"
How can I solve the problem?
Thank you in advance

1

There are 1 answers

0
M. Eriksson On

When you use namespaces, PHP will assume that any class you load is under that namespace as well, unless you've imported it.

Example:

namespace Foo;

$bar = new Bar;

This will assume that Bar also is under the namespace Foo.

If the class you're using is under another namespace, or not in a namespace at all (the global namespace), you need to tell PHP which class to use by importing it. You do this with the use

namespace Foo;

use Bar;

$bar = new Bar;

So in your case, it should be:

namespace Fromtify\Database {
    use R;

    R:setup(...);
    // The rest of your code

}

Side note!_

Unless you have multiple namespaces in the same file, which you usually don't have, there's not need for the syntax:

namespace Foo {
    // your code
}

You can simpy do:

namespace Foo;

// Your code.

...which makes the code a bit cleaner.

You can read more about defining namespaces and using namespaces in the manual