1

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.

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

4 Comments

interesting, this would work case-insensitive? So it would set $foo->Var (capital V) when the query looks like the one you posted?
If you need it to be case insensitive, you can always use php's strtolower assuming everything is lowercase. For example: $index = strtolower($index); $foo->{$index}. @user2177707 - Do your object properties follow a naming convention? Like all lowercase except the first letter, all uppercase, etc?
CamelCase, which makes it hard to determine the format automatically (hence my despair. :) ).
@user2177707 - Please see my revised answer. Though not super efficient, this will work for finding out if a property exists in your object. This will not work if you have two properties that evaluate to the same lowercase string: e.g. CamelCase and CAMELcase, but that would be a poor design strategy anyways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.