PHP advanced function (Function)

  • reference parameter
$name = "eko";
function chang_name(&$name){
    $name .= '_after_change';
}    
chang_name( $name );     // will change the original parameter $name 
echo  $name ;
  • parameter type declaration
function test(array $arr){
    for ($i=0; $i <count($arr) ; $i++) { 
        echo $arr[$i] .'</br>';
    }
}
test( 'hello' ); error

interface Animal {
    function eat();
    function sleep();
}

class Cat implements Animal{
    public function eat(){
        echo "cat eat fish";
    }
    public function sleep(){
        echo "cat is sleeping";
    }
}

function fn(Animal $animal){
    echo $animal -> eat();
}

fn(new Cat());
  • variable parameter
function fn(){
     $arg_nums = func_num_args (); //Get the number
     of parameters echo "Pass in $arg_nums parameters at this time " ;
     echo "</br>" ;

    $arr_args = func_get_args ();     // Get all parameters, return array 
    echo  gettype ( $arr_args ) ."</br>";    // Output array

    foreach ($arr_args as $arg) {
        echo $arg."</br>";
    }

    $arg = func_get_arg (0);         // Get the 0th parameter 
    echo  $arr_arg ;
}
fn('hello',123);
// In PHP 5.6 and above, the variable argument can be replaced by the spread operator 
function fn(... $args ){
     echo "input ". count ( $args )." arguments" ;
     echo '</br> ' ;
     for ( $i =0; $i < count ( $args ) ; $i ++ ) { 
         echo  $args [ $i ] .'</BR>' ;
    }
}
fn('hello','word',123);
fn( ...['hello','word',123]); // The result is the same as above

//If there are multiple arguments, variable arguments must be placed at the end 
function fn( $name ,... $args ){
     echo  $name .'</br>' ;
     for ( $i =0; $i < count ( $args ) ; $i ++ ) { 
         echo  $args [ $i ] .'</BR>' ;
    }
}
fn('kitty','yellow','miao');
  • return type
// php7 supports function return value type declaration 
function sum(... $args ): int{
     $sum = 0 ;
     foreach ( $args  as  $value ) {
         $sum += $value ;
    }
    return $sum;
    //return 'hello'; //报错,Return value of sum() must be of the type integer
}
echo sum(1,2,3,4,5);
  • Anonymous function (Closure function Closure)
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
} , 'hello-world' );
 // output helloWorld

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325304718&siteId=291194637