Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate a class in a case-insensitive way

Tags:

oop

php

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:

  • I have a class_exists() check (case insensitive) before this snippet to make sure that the class I want actually exists.
  • The class name is always properly camel-cased (e.g. MySuperAwesomeClass).
like image 467
3rgo Avatar asked Feb 16 '23 17:02

3rgo


1 Answers

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";
}




?>
like image 190
Hanky Panky Avatar answered Feb 27 '23 04:02

Hanky Panky