简体   繁体   English

PHP在另一个名称空间的类中的方法内部使用名称空间类

[英]PHP use namespace class inside method in a class of another namespace

Is it possible in some way to instantiate a class inside a namespace, in a method in another class inside another namespace? 是否可以通过某种方式实例化名称空间内的类,在另一个名称空间内的另一个类的方法中? And with the requested class instantiated from a variable? 并从变量实例化请求的类?

Example : 范例

Class to be loaded from loader-class : 要从loader-class加载的类

namespace application/pages;

class loader
{
    private function __construct()
    {
        echo 'Class loaded...';
    }
}

Loader-class : 装载机类

namespace system/loader;

class loader
{
    private $vars;

    private function __construct($vars)
    {
        $this->vars = $vars;
    }

    private function load_class()
    {
        require(CLASSES . $this->vars['namespace'] . '/' . $this->vars['class'] . ".php");

        use $this->vars['namespace'];
        return new \$this->vars['namespace']\$this->vars['class']();
    }
}

Sorry for the bit confusing formulation, but i couldn't think of better way to ask the question. 抱歉,我的表述有点令人困惑,但我想不出更好的方法来提问。

Thanks. 谢谢。

This is the general way to load in namespaces: http://www.php.net/manual/en/function.spl-autoload.php 这是在命名空间中加载的一般方法: http : //www.php.net/manual/en/function.spl-autoload.php

However there is a more popular way of doing it using Composer . 但是,有一种使用Composer的更流行的方法。

  1. Download composer.phar and inside your project directory run: php composer.phar init 下载composer.phar并在项目目录中运行: php composer.phar init
  2. Following the interactions. 跟随互动。
  3. In your project root, create a src directory then add this to your composer.json file which generated: "autoload": { "psr-0": { "": "src/" } } 在您的项目根目录中,创建一个src目录,然后将其添加到您的composer.json文件中,该文件生成: "autoload": { "psr-0": { "": "src/" } }

Your composer.json file should now look like this: 您的composer.json文件现在应如下所示:

{
    "name": "acme/sample",
    "authors": [
        {
            "name": "Person",
            "email": "person@example.com"
        }
    ],
    "minimum-stability": "dev",
    "autoload": {
        "psr-0": { "": "src/" }
    },
    "require": {

    }
}
  1. Run: php composer.phar install , which will generate a vendors directory and an autoload script. 运行: php composer.phar install ,它将生成供应商目录和自动加载脚本。

  2. Create your primary load php file and include the autoload.php file inside. 创建您的主要加载php文件,并在其中包含autoload.php文件。

Now, your namespaces inside the src directory and any imported libraries in vendor, will be exposed to your application. 现在,您的src目录中的名称空间以及供应商中任何导入的库将公开给您的应用程序。

Checkout symfony/symfony-standard to see a full framework example. 签出symfony/symfony-standard以查看完整的框架示例。

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

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