0

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 ; ?

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

OP - This works because your array is what's known as an associative array. Your $controller variable is actually referencing the key of that array, so you can access the value the same way you would with an indexed (numbered) array - array[key].
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.