PHP: Executing a method conditionally

We’re going back to using when and unless

Photo by Eliobed Suarez on Unsplash

When I was coding something, I needed to execute a method in a class when a value was evaluated to truthy.

Practically speaking, the Transport received a package, and depending on the conditions of the package, it would handle it differently. Also, if the weather was dangerous (snowing, tornados or Godzilla), it should notify the user for possible delays.

The code is not that pretty to read, at least for me.

if ($package->isBig()) {
if ($package->isFragile()) {
if ($weather->isDangerous()) {
return $transport->deliver();

While this is lexically correct and understandable, I decided to go the extra mile and try to one-line everything, not using a callable as my previous article allowed to.

Instead, call the next method depending on the result of the previous method value.


Welp, I can do that.

Catching the next method, programatically

The only way to do this is to trap the object we’re using into another, with the value that is evaluated.

To trap this, we can simply use an empty “Container” object that will hold the object, and the value being evaluated. The next method will be executed on this object. Since it will be catched by the __call magic method, we can pass the method name and its arguments to the underlying target if it should or not depending on the value we pushed before.

The “container” class looks like this:

And the way we can call it in any class is by creating a method called when(), which will instance a new Container object containing the target object.

public function when($value)
return new Container($this, $value);

We can do amazing things with this snippet, making large lines into one, without growing methods into unscrupulous text walls full of if chains that break the flow of a class call.

Some may want to use the old way, and it’s okay because they may have been accustomed to the old way, but be wary that large methods with dozens of lines adds complexity to read, and some people are not okay with that (like me), especially when you’re in charge of writing and maintaining it.

You can find this trait and other helpers in my Laratraits package. Give it a chance if you find something useful to use in your project.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Italo Baeza Cabrera

Italo Baeza Cabrera


Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.