3rgo
3rgo

Reputation: 3153

Instantiate a class in a case-insensitive way

I'm faced with a bit of an issue. I have my class name in a variable and I need to instantiate it, but I have no way of knowing that my variable has the exact same case than the class.

Example:

//The class I'm fetching is named "App_Utils_MyClass"
$var = "myclass";
$className = "App_Utils_".$var;
$obj = new $className();

How can I make this work?

Additional info:

Upvotes: 4

Views: 1050

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

Contrary to the popular belief, function names in PHP are not case-sensitive, same for a class constructor. Your case should already work. Try this

<?php
class TestClass {
    var $testValue; 
}


$a=new testclass();
$b=new TestClass();
$c=new TESTCLASS();
print_r($a);
print_r($b);
print_r($c);

?> 

According to PHP Manual

Note: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

This applies to your class methods aswell.

Workaround/Better way to Name those Classes

The following will ensure that the class name will always be in the exact case as was defined by you, doesn't matter in which case user enters it

<?php       
class TestClass {
    var $testValue; 
}


$userEnteredValue="testCLASS";
$myClasses=get_declared_classes();
$classNameIndex=array_search(strtolower($userEnteredValue), array_map('strtolower', $myClasses));
if($classNameIndex!==FALSE)
{
    $classNameShouldBe=$myClasses[$classNameIndex];
      echo $classNameShouldBe;
}
else
{
    echo "This class is undefined";
}




?>

Upvotes: 8

Related Questions