Sune
Sune

Reputation: 677

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.

Upvotes: 1

Views: 1348

Answers (1)

Flosculus
Flosculus

Reputation: 6956

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": "[email protected]"
        }
    ],
    "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.

Upvotes: 1

Related Questions