0
<?php
    class A{
        function __call($name,$num){
            echo "Method name:".$name."<p>";
            echo "the number of parameter:".count($num)."<p>";
            if(count($num)==1){
                echo $this-> list1($a);
            }
            if(count($num)==2){
                echo $this-> list2($a,$b);
            }
        }
        public function list1($a){
            return "this is function list1";
        }
        public function list2($a,$b){
            return "this is function list1";
        }
    }
    (new A)->listshow(1,2);
?>

(php overload) set two functions for the class member to choose. But have a mistake, it show that

Undefined variable: on line 10.

Why?

Qirel
  • 25,449
  • 7
  • 45
  • 62
John Young
  • 57
  • 1
  • 8

1 Answers1

1

You're trying to call list2() from within __call() using args $a and $b but these aren't defined anywhere in __call()

Instead, you need to pass the $num array.... personally I'd prefer to call it $args... and use the ... operator for argument packing

class A{
    function __call($name, $args){
        echo "Method name:".$name."<p>";
        echo "the number of parameter:".count($args)."<p>";
        if(count($args)==1){
            echo $this-> list1(...$args);
        }
        if(count($args)==2){
            echo $this-> list2(...$args);
        }
    }
    public function list1($a){
        return "this is function list1 with $a";
    }
    public function list2($a,$b){
        return "this is function list2 with $a and $b";
    }
}
(new A)->listshow(1,2);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385