Laravel 5 String Helpers: Parse Callback

2 min read

parseCallback is a fairly simple method, even though it serves a somewhat specialized purpose. The following syntax for class names and method names can be found utilized throughout the Laravel framework:

1ClassName@someMethodName

The point is that there is a string, split by the @ symbol, with the class name on the left and a method name on the right. We can use the parseCallback method to break up this string, and also specify a $default method name. If there is nothing on the right hand side of the @ symbol, or if there is no @ symbol, the $default is used as the returned method name.

The function returns an array, with two elements. The first element is the class name, and the second element will be the method name.

Signature

The signature of the parseCallback method is:

1public static function parseCallback(
2 $callback,
3 $default = null
4 );

Example Use

The following examples will highlight the values that might be returned from this function:

1use Illuminate\Support\Str;
2 
3Str::parseCallback('MyClass', 'defaultValue');

The return value would be:

1array(2) {
2 [0] "MyClass"
3 [1] "defaultValue"
4}
1use Illuminate\Support\Str;
2 
3Str::parseCallback('MyClass@method', 'defaultValue');

The return value would be:

1array(2) {
2 [0] "MyClass"
3 [1] "method"
4}
1use Illuminate\Support\Str;
2 
3Str::parseCallback('MyClass@method@somethingElse', 'defaultValue');

The return value would be:

1array(2) {
2 [0] "MyClass"
3 [1] "method@somethingElse"
4}

It is with this example that it becomes obvious that the parseCallback will only observe the first @ symbol. Anything after the first occurrence of the @ symbol will become part of the method name returned.

1<?php
2 
3use Illuminate\Support\Str;
4 
5Str::parseCallback('', '');

The return value would be:

1array(2) {
2 [0] ""
3 [1] ""
4}

An example use of this function could look like this:

1<?php
2 
3use Illuminate\Support\Str;
4 
5class MyClass {
6 
7 /**
8 * Returns a hello message.
9 *
10 * @return string
11 */
12 public static function sayHello()
13 {
14 return 'Hello';
15 }
16 
17}
18 
19// Would send 'Hello' to the screen.
20echo call_user_func(Str::parseCallback('MyClass@sayHello'));

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch