imperium2335
imperium2335

Reputation: 24112

Access array key value without specifying the key

I have:

public $staticRoutes = array(
        'dog-toys' => 'Index',
        ) ;

if(array_key_exists($controller, $this->staticRoutes))
{
    $controller = new $controller ;
}

The new $controller is becoming 'dog-toys', which is not what I want.

How can I change what I have so that $controller = new Index ; ?

Upvotes: 0

Views: 67

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

You would need to actually use you $staticRoutes array like this:

$controller_instance = new $this->staticRoutes[$controller];

Note I changed the name of the variable you are assigning to for clarity's sake. I am also assuming that the code trying to instantiate this controller is in the same class (or inheriting class) where the $staticRoutes property is defined (thus the use of $this).

Upvotes: 1

jeroen
jeroen

Reputation: 91734

Some variation of:

$controller = new ${staticRoutes[$controller]} ;

I cannot test it right now, so to be safe you could also do:

$ctrl = $staticRoutes[$controller];
$controller = new $ctrl;

Upvotes: 2

Related Questions