简体   繁体   中英

Undefined type 'Fromtify\Database\R'

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

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 theuse

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 andusing namespaces in the manual

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM