undefinedfix
Sign in

Don't understand the new $people();

user14832020 edited in Sat, 21 May 2022

A section of PHP code simulates the hook mechanism

    class Ball{  
          public $people;
          public function down(){  
            echo    "ball is downing ";  
            //注册事件  
            $this->people=new Hook();
            $this->people->add("man");  
            $this->people->add("woman");  
        }  
          
        public function do(){  
            $this->people->exec();  
        }     
      
    }  
      
    // 钩子的定义  
    class Hook{  
        private $hooklist = null ;  
        // 添加  
        public  function add($people){         
            $this->hooklist[] =  new $people();        
        }  
        // 触发事件  
        public function exec(){  
            foreach($this->hooklist as $people){  
                  $people->act();
            }  
              
        }  
    }  
    // 钩子实现  
    class man{  
        public function act(){  
            echo 'nothing';  
        }     
    }  
      
    class woman{  
        public function act(){  
            echo 'oh my god ';  
        }     
    }  
      
      
    $ball = new Ball();  
    $ball ->down();  
    $ball ->do();  
    

这里的new $people()是一种什么用法?
没有这个people类哈


        public  function add($people){         
        $this->hooklist[] =  new $people();        
    }  
2 Replies
dinara_pulseway
commented on Sat, 21 May 2022

$people ='Man ';, new $people(); equivalent to new man();

$people ='woman ';, new $people(); equivalent to new woman();

Justallstar
commented on Sat, 21 May 2022

Don't you see that a $is added in front of people, which means that it is only a variable, but the value of this variable may be combined with the new operation, which is an instance of a function

lock This question has been locked and the reply function has been disabled.