简体   繁体   中英

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 :

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

However there is a more popular way of doing it using Composer .

  1. Download composer.phar and inside your project directory run: 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/" } }

Your composer.json file should now look like this:

{
    "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.

  2. Create your primary load php file and include the autoload.php file inside.

Now, your namespaces inside the src directory and any imported libraries in vendor, will be exposed to your application.

Checkout symfony/symfony-standard to see a full framework example.

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