Calling a function within a Class method?

前端 未结 10 1002
庸人自扰
庸人自扰 2020-12-02 05:14

I have been trying to figure out how to go about doing this but I am not quite sure how.

Here is an example of what I am trying to do:

class test {
          


        
相关标签:
10条回答
  • 2020-12-02 06:09
    class test {
        public newTest(){
            $this->bigTest();
            $this->smallTest();
        }
    
        private  function bigTest(){
            //Big Test Here
        }
    
        private function smallTest(){
           //Small Test Here
        }
    
        public scoreTest(){
          //Scoring code here;
        }
     }
    
    0 讨论(0)
  • 2020-12-02 06:11

    example 1

    class TestClass{
    public function __call($name,$arg){
    call_user_func($name,$arg);
    }
    }
    class test {
         public function newTest(){
    
              function bigTest(){
                   echo 'Big Test Here';
              }
              function smallTest(){
                   echo 'Small Test Here';
              }
    
    $obj=new TestClass;
    
    return $obj;
         }
    
    }
    $rentry=new test;
    $rentry->newTest()->bigTest();
    

    example2

    class test {
         public function newTest($method_name){
    
              function bigTest(){
                   echo 'Big Test Here';
              }
              function smallTest(){
                   echo 'Small Test Here';
              }
    
          if(function_exists( $method_name)){    
    call_user_func($method_name);
          }
          else{
              echo 'method not exists';
          }
         }
    
    }
    $obj=new test;
    $obj->newTest('bigTest')
    
    0 讨论(0)
  • 2020-12-02 06:15

    To call any method of an object instantiated from a class (with statement new), you need to "point" to it. From the outside you just use the resource created by the new statement. Inside any object PHP created by new, saves the same resource into the $this variable. So, inside a class you MUST point to the method by $this. In your class, to call smallTest from inside the class, you must tell PHP which of all the objects created by the new statement you want to execute, just write:

    $this->smallTest();
    
    0 讨论(0)
  • 2020-12-02 06:19

    In order to have a "function within a function", if I understand what you're asking, you need PHP 5.3, where you can take advantage of the new Closure feature.

    So you could have:

    public function newTest() {
       $bigTest = function() {
            //Big Test Here
       }
    }
    
    0 讨论(0)
提交回复
热议问题