0

I want to be able to look for and alter specific properties that may or may not exist in a given object. These properties are part of an inconsistently structured array, so I want to define ahead of time what properties to look for.

$properties = array(
  "color",
  "name['first']",
  "jobs->primary['company']",
  "location['home']['city']",
  etc...
);

foreach ($properties as $property) {
  if (isset($some_object->$property)) {
    ...
  }
}

The problem is, of course, with '$some_object->$property' which is always null.

I assume $property is being treated as a string rather than a variable name. I just don't recall if there's way to indicate that it's part of the variable name and not a simple string.

Thanks!

2
  • So, with "location['home']['city']", do you expect to get $some_object->location['home']['city'], or $some_object->{"location['home']['city']"}? Commented Apr 3, 2015 at 23:11
  • I want to access $some_object->location['home']['city'] Commented Apr 4, 2015 at 23:30

2 Answers 2

2

Your code will work if your object looks something like this:

$some_object = new stdClass;
$some_object->{"color"} = "brown";
$some_object->{"name['first']"} = "Bob";
$some_object->{"jobs->primary['company']"} = "Google";
$some_object->{"location['home']['city']"} = "Redmond";

If your object looks like this:

$some_object = new stdClass;
$some_object->color = "brown";
$some_object->name = ["first" => "Bob"];
$some_object->jobs = new stdClass;
$some_object->jobs->primary = ["company" => "Google"];
$some_object->location = ["home" => ["city" => "Redmond"]];

Then your code will not work.

The values in the $properties array are strings, not object properties/arrays. In order to use the $properties values you need to write quite a bit of code that parses the values ("makes sense of" the values), and then you would need to use the parsed data to recursively walk the object.

Recursively walking the object is not that difficult, but you would be better off finding some other way of doing it.

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

1 Comment

I thought there was some way to use a string value to reference nested properties using {}. I also don't think recursing the array would help as I'd still have to access values using the passed in 'property strings'.
0

For this you can use the function property_exists

So it would be:

foreach ($properties as $property) {
  if (property_exists($object ,$property )) {
    ...
  }
}

1 Comment

My question is what syntax would be used to access the property.

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.