phpoopmethod-call

Call a method from another method within the same class in PHP


I am struggling to implement a php code with the following structure:

public function hookActionValidateOrder($params)
{
     $invoice = new Address((int)$order->id_address_invoice);
     $myStreet = $invoice->address1;
     $myCity = $invoice->city;
     $myPostcode = $invoice->postcode;

     // ... SOME IRRELEVANT CODE HERE ...
  
     $Tid = send($myStreet, $myCity, $myPostcode); /* Calling function send($a, $b, $c) */
}

public function send($a, $b, $c)    /* function send($a, $b, $c) */
{
     // ... CODE TO DO SOMETHING USING VARIABLES $a, $b, $c ...
}

The problem is, this code doesn´t seem to work. When I put it into a code validator, it says: "Function 'send()' does not exists". Why is that so and how do I fix that?


Solution

  • If you are using a class, then you can use $this for calling the function:

    class Test {
    
        public function say($a) {
            return $a ;
    
        } 
    
        public function tell() {
            $c = "Hello World" ;
            $a = $this->say($c) ;
            return $a ;
        }
    } 
    
    $b= new Test() ;    
    echo $b->tell() ;
    

    If you are using a normal function, then use closure:

    function tell(){
       $a = "Hello" ;
       return function($b) use ($a){
          return $a." ".$b ;
       } ;  
    }
    
    $s = tell() ;
    echo $s("World") ;