Bin Emmanuel
Bin Emmanuel

Reputation: 93

Instantiating an Object using a variable in PHP 7

On my Local Machine, running Win 10, PHP 7.4 the below code works but not on my production server even though I've got same PHP version on both.

<?php
use controller\Admin;

$ct_name = 'controller'. DIRECTORY_SEPARATOR . ucfirst($this->url[0]);

$controller = new $ct_name();

I tried something sometimes ago that worked but I can't remember what I did.

Upvotes: 0

Views: 37

Answers (1)

L00_Cyph3r
L00_Cyph3r

Reputation: 669

It look like your DIRECTORY_SEPARATOR is the issue, unless you're on Windows the DIRECTORY_SEPARATOR is a forward slash where a namespace separator needs to be a backward slash.

I quickly edited your code so you can give it a try:

<?php
use controller\Admin;

$ct_name = 'controller\\' . ucfirst($this->url[0]);

$controller = new $ct_name();

Note that when using backslashes in strings the almost always need to be escaped.

Upvotes: 1

Related Questions