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:
class_exists()
check (case insensitive) before this snippet to make sure that the class I want actually exists.MySuperAwesomeClass
).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";
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With