PHP - Accessing object properties without case sensitivity?

I am working on an old application in which there are many inconsistencies in the naming conventions used.

Is there a way to access object properties that ignore case sensitivity?

For example, I have an object called currentuser with the Name attribute.

Is there any way to get this value as follows?

$currentuser->name

Any advice is appreciated.

Thanks.

+5
source share
4 answers

Well, you can write a function __getfor each of your classes that will handle such a conversion, but these are pretty hacks. Maybe something like this:

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

, , , . , :

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

. .

+3

( , ), . - , , .

function findPropertyNameCaseInsensitive($obj, $name)
{
  $propertyNames = array_keys(get_object_vars($obj));
  foreach($propertyNames as $propertyName)
  {
    if (strcasecmp($name, $propertyName) == 0)
      return $propertyName;
  }
  return NULL;
}
+3
0

I know this is an old post, but I thought that I would throw another solution. At first I tried to use the get_class_vars method, but decided to use it instead array, and then use it array_change_key_caseto convert the keys to lowercase. At this point, you can either work with the array or convert it back to an object. I have not done any tests, but I am dealing with small objects.

function convertPropNamesLower($obj) {
    return (object)array_change_key_case((array)$obj, CASE_LOWER);
}

//usage
$myObj = convertPropNamesLower($myObj);
echo $myobj -> myprop;
0
source

All Articles