Search

Laravel String Helper Function: parse_callback

November 16, 2016 —John Koster

The parseCallback helper method 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 signature for the parseCallback helper function is:

parseCallback($callback, $default)

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

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 
2use Illuminate\Support\Str;
3 
4Str::parseCallback('', '');

The return value would be:

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

An example use of this function could look like this:

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

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.