1

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.

2
  • Seems inefficient, why are you trying to do it this way? Commented Jan 14, 2014 at 12:32
  • Because i have a router class that i want to load the current page. But a workaroud or suggestion to another way of doing it would be great. ;) Commented Jan 14, 2014 at 12:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.