I'm working on an old app where there is a lot of inconsistency in the naming conventions used.
Is there a way to access object properties that ignores case sensitivity?
For example, I have an object called currentuser with the attribute Name.
Is there any way to retrieve that value like this?
$currentuser->name
Any advice appreciated.
Thanks.
The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!
In PHP, class names as well as function/method names are case-insensitive, but it is considered good practice to them functions as they appear in their declaration.
In PHP, variable and constant names are case sensitive, while function names are not.
While object properties are strings and they are case sensitive, you could use an own standard and use only lower case letters for the access. You could apply a String#toLowerCase to the key and use a function as wrapper for the access.
Well, you can write a __get
function to each of your classes that would handle such a conversion, but it's quite hacky. Something like this might work:
class HasInconsistentNaming {
var $fooBar = 1;
var $Somethingelse = 2;
function __get($var) {
$vars = get_class_vars(get_class($this));
foreach($vars as $key => $value) {
if(strtolower($var) == strtolower($key)) {
return $this->$key;
break;
}
}
return null;
}
}
Now, you can do this:
$newclass = new HasInconsistentNaming();
echo $newclass->foobar; // outputs 1
If you want to simplify your task a bit you can have your base classes inheriting from a class that provides this functionality. This way you don't have to write the function to each of your classes:
class CaseInsensitiveGetter {
function __get($var) {
$vars = get_class_vars(get_class($this));
foreach($vars as $key => $value) {
if(strtolower($var) == strtolower($key)) {
return $this->$key;
break;
}
}
return null;
}
}
class HasInconsistentNaming extends CaseInsensitiveGetter {
var $fooBar = 1;
var $Somethingelse = 2;
}
But I'd strongly discourage you from taking this approach. In the long run, it would be much smarter to just convert all variables into a consistent naming scheme.
If you have no control over the object (maybe it's a row from an external database), i would recommend to find out the correct names before you access the rows. The function below is not a cheap operation, but done only the first time, it can make your application more stable.
function findPropertyNameCaseInsensitive($obj, $name)
{
$propertyNames = array_keys(get_object_vars($obj));
foreach($propertyNames as $propertyName)
{
if (strcasecmp($name, $propertyName) == 0)
return $propertyName;
}
return NULL;
}
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