Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function from another function in PHP

Tags:

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". Tell me please Why is that so and how do I fix that?

like image 428
BB-8 Avatar asked Feb 23 '17 04:02

BB-8


People also ask

How can I call a PHP function from another function?

$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 ... }

How can I call PHP function inside PHP?

There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var );

How can I access one function variable from another function in PHP?

You could set a return value from the first function which could either be passed as a parameter to the second function or declared, within the second function, as a global. Save this answer.

Can we use function in function PHP?

You can also define a function within another function and logically this too should be a local variable but recall the rule that all functions are global. In PHP inner functions are global and hence behave in the same way as if they had been declared outside of any containing function.


1 Answers

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") ; 
like image 115
gaurav Avatar answered Sep 30 '22 17:09

gaurav