繁体   English   中英

在父名称空间中使用PHP类

[英]Using PHP class in parent namespace

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

所以我有一个名为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类内的所有功能?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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