PHP引用变量,不区分大小写的字符串


PHP reference variable by case-insensitive string

我在一种情况下,我需要翻译一个不区分大小写的url查询到一个PHP对象的成员变量。基本上,我需要知道url查询键指向的成员变量,这样我就可以知道它是否是数字。

例如:

class Foo{
    $Str;
    $Num;
}
myurl.com/stuff?$var=value&num=1

在处理此URL查询时,我需要知道"str"与Foo->$ str等相关联。对如何处理这个问题有什么想法吗?我什么也想不出来

试试这样做。

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

看一下php关于类和对象的文档可能会有帮助。

例子:

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

那么$_GET看起来是这样的:

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

通过循环,我们将检查$foo是否具有属性var, ($foo->var)以及它是否具有属性num ($foo->num)。