PHP - Check if global class exists inside namespac

2019-07-18 02:17发布

How can you check if a global class exists with class_exists if you are inside the namespace of another class? For example:

<?php
namespace Rvdv\Test\Example;

class ExampleClass
{
    public function testNamespace()
    {
        // This says that it doesn't exists :(
        print class_exists('\\Test');
    }
}

Where class is a global defined class.

1条回答
爷的心禁止访问
2楼-- · 2019-07-18 02:28

You've had to screw up something in your other issues - most likely the class test is not declared in this scope (did you forget include?). I tested this thusly:

phpcltest2.php:

<?php
class Test { }

phpcltest.php:

<?php
namespace Rvdv\Test\Example;
require 'phpcltest2.php';

class ExampleClass
{
    public function testNamespace()
    {
    print class_exists('\\Test');
    }
}

$nc = new ExampleClass();
$nc->testNamespace();

The results were expected: it prints out "1". So check your include paths.

查看更多
登录 后发表回答