在父命名空间中使用PHP类

时间:2016-12-16 07:18:49

标签: php

我只是想绕过整个概念。我试图将频繁/全局使用的类属性和方法放在最上面的命名空间中,并在其他类中使用它们。

所以我有一个名为App的名称空间:

文件名:core.php

namespace App;

class Core {

    public function version() {
      return '1.0';
    }

}

文件名:settings.php

namespace App\Core;

use Core; // I know this is wrong

class Settings {

    public function getCurrent() {
      return 'The current version is: '.$this->Core->version(); // How do I do this?
    }

}

文件名:index.php

include('core.php');
include('settings.php');

$app = new App\Core;

echo $app->version(); // 1.0 OK...
echo $app->settings->getCurrent(); // Echo: The current version is: 1.0

所以在上面的例子中,我如何在其他命名空间中的其他类内部的应用程序中使用Core类内的所有函数?

1 个答案:

答案 0 :(得分:0)

现在无法测试,但我会做这样的事情:

core.php中

namespace App;

class Core {

    public static function version() {
      return '1.0';
    }

}

然后是Settings.php

    require('Core.php');

    class Settings {

        public function getCurrent() {
          return 'The current version is: '.Core::version(); 
        }

    }

最后:

include('Core.php');
include('Settings.php');

$app = new Settings;

echo Core::version() // 1.0 OK...
echo $app->settings->getCurrent(); // Echo: The current version is: 1.0