0

I was looking at the codebird-php git and noticed that the author has a way to detect methods that are not declared in the class itself. For example, he has

$cb->statuses_homeTimeline();

which successfully executes, despite there not being a method called statuses_homeTimeline() in the Codebird class.

I've tried looking for information regarding this type of construction, but without knowing what it's called, I haven't found anything.

What is it generally called (I've googled all variations of "variable methods," "mapping methods," etc)? Are there arguments against its use? How does it (in principle) work?

1
  • 5
    You are looking for the "magic method" __call. Commented May 12, 2014 at 22:04

2 Answers 2

4

I found a bunch of questions involving __call and things you can do with it, but nothing about what __call actually is.

PHP objects have a number of Magic Methods. The most well-known being __construct.

__call is a magic method which gets called whenever you try and call a method that doesn't exist. It's sort of a "catch-all" for methods.

The technical term is "Method Overloading".

So when $cb->statuses_homeTimeline() is called, if that method does not exist, it will instead call
$cb->__call("statuses_homeTimeline",array())

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

5 Comments

This is freaking awesome. PHP never ceases to amaze me. Are there any reasons to not use it?
It's a catch-all, so you need to be sure that whatever you receive is valid input. Other than that, not really.
@jboneca: There are plenty of reasons to not do it. Let's start with a counter-question: how exactly is $cb->statuses_homeTimeline() better than $cb->whatever('statuses', 'homeTimeline')? There's less typing, but is less typing "freaking awesome"? Of course, there are also reasons for it. As in all things, you must find a balance.
@Jon It seems to me that __call() is a built-in way of doing $cb->whatever('statuses', 'homeTimeline'). To me they seem synonymous with the exception that the former is ready-to-go.'
@jboneca: Suppose there are whatever1, ... whatever20 methods. Does replacing all of them with __call sound like a good idea? What about 19 methods? 18? Obviously stuff is being put on the scales and at some indeterminate point it tips them.
1

__call() magic method. __call() is triggered when invoking inaccessible methods in an object context.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.