0

I was wondering if the following is possible. We have a class that is design to used chained methods.

$CarClass = $CarConnection->models->count();

In the above example we are counting the models. However, want to do it dynamically. So for instance:

$CountArray = array('models','brands','countries');
foreach($CountArray AS $key => $value){
    $CarData[$value] = $CarConnection->$value->count();       
}

However, this outputs an error: "Call to a member function count() on a non-object in" While i'm pretty sure the count exists as the earlier mention function is working.

Some googling led to add brackets { } but that doesn't work either.

 $CarData[$value] = $CarConnection->{$value}->count();    

Any one a solution?

Kind regards,

Peter

2
  • Looks like you are getting null (or any other result except object) while you are trying to access one of the properties (models, brands, or countries) or magic method (if any) __get of the $CarConnection class does not return the object. The call $CarConnection->{$value}->count(); is correct. Commented Feb 20, 2015 at 10:50
  • Make sure $CarConnection has the model, brands and countries properties and they are objects that expose the count() method. The error message say you are calling count() on a value that is not an object. It may be NULL or something else (array, string, integer etc.) Commented Feb 20, 2015 at 10:59

1 Answer 1

1

I can spot a syntax error in your loop: It should go -

$CountArray = array('models','brands','countries');

foreach($CountArray as $key => $value){
$CarData[$value] = $CarConnection->$value->count();       

}

And also, the array you have is not an associative one. So you don't need $key! Try this:

foreach($CountArray as $value) {
 $CarData[$value] = $CarConnection->{$value}->count();
}
Sign up to request clarification or add additional context in comments.

1 Comment

With the syntax error changed, the error remains. (Corrected in the Answer).

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.