简体   繁体   中英

PHP reference variable by case-insensitive string

PHP 5. I'm in a situation where I need to translate a case-insensitive url query to member variables in a PHP object. Basically, I need to know what member variable the url query key points to so I can know if it's numeric or not.

For example:

class Foo{
    $Str;
    $Num;
}

myurl.com/stuff?$var=value&num=1

When processing this URL query, I need to know that "str" associates with Foo->$Str, etc. Any ideas on how to approach this? I can't come up with anything.

Try something like this.

function fooHasProperty($foo, $name) {
  $name = strtolower($name);
  foreach ($foo as $prop => $val) {
    if (strtolower($prop) == $name) {
      return $prop;
    }
  }
  return FALSE;
}

$foo = new Foo;

// Loop through all of the variables passed via the URL
foreach ($_GET as $index => $value) {
  // Check if the object has a property matching the name of the variable passed in the URL
  $prop = fooHasProperty($foo, $index);
  // Object property exists already
  if ($prop !== FALSE) {
    $foo->{$prop} = $value;
  }
}

And it may help to take a look at php's documentation on Classes and Objects .

Example:

URL: myurl.com/stuff?var=value&num=1

Then $_GET looks like this:

array('var' => 'value', 'num' => '1')

Looping through that, we would be checking if $foo has a property var , ( $foo->var ) and if it has a property num ( $foo->num ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM