Home > Enterprise >  PHP - How to call multiple functions of a class on top of each other
PHP - How to call multiple functions of a class on top of each other

Time:10-27

How to create a class that can call multiple functions?

example:

class ClassName
{
    public static function func1()
    {
    }

    public static function func2()
    {
    }

    public static function func3()
    {
    }

}

ClassName::func1()->func2()->func3();

result Uncaught Error: Call to a member function funcX() on null

CodePudding user response:

This won't work at all with static methods as you suggest.

This is possible however with an instance object, that is called "builder pattern" or "fluid style":

<?php
class ClassName {
    public function func1(): ClassName {
      echo "1";
      return $this;
    }

    public function func2(): ClassName {
      echo "2";
      return $this;
    }

    public function func3(): ClassName {
      echo "3";
      return $this;
    }
}

(new ClassName())->func1()->func2()->func3();

The output is:

123

CodePudding user response:

In PHP you cannot call static functions "piggybacked" like you can in, say, JavaScript. You have a few options .. Call them in a list, one at a time .. Like so:

ClassName::func1();
ClassName::func2();
ClassName::func3();

Or Like

$foo = new ClassName;
$foo->func1();
$foo->func2();
$foo->func3();

Now if you want to run them all with a single call, you need to nest the functions BUT we have to rid ourselves of the static method ...

<?php

class ClassName
{
   public function func1()
   {
     echo "1 \n";
     $this->func2();
   }
   public function func2()
   {
     echo "2 \n";
     $this->func3();
   }
   public function func3()
   {
     echo "3 \n";
   }

}

$foo = new ClassName;
$foo->func1();

Finally, if you want to run all of your functions within a class sequentially, you can use get_class_methods and loop through all the functions ... IE

<?php

class ClassName
{
   public static function func1()
   {
      echo "1 \n";
   }
   public static function func2()
   {
      echo "2 \n";
   }
   public static function func3()
   {
      echo "3 \n";
   }
}

$functions = get_class_methods('Classname');

foreach ($functions as $function){
    ClassName::$function();
} 

Both methods will result in:

1
2
3

If you choose to rid yourself of the static method however (as seen in our "nested function").. And you just choose public .. Then your syntax is possible using @arkascha's method of building out.

 public function func1(): ClassName { // From @arkascha's answer .. 

 $foo = new ClassName;
 $foo->func1()->func2()->func3();

The difference is understanding public method and static method

  • Related