PHP Function

梦想的初衷 提交于 2020-01-27 00:11:01
<?php
//1.require(fatal error) and include(warning error)
          echo 'This is the main file.<br />';
          require('reusable.php');
          echo 'The script will end now.<br />';
          /*
           there are three situations here
          1. if the reusable.php are those codes, which includes php tags
                    <?php
                  echo 'Here is a very simple PHP statement.<br />';
                  ?>
            then, codes will be processed by php engine, finally
                   <?php
                  echo 'This is the main file.<br />';
                   echo 'Here is a very simple PHP statement.<br />';
                  echo 'The script will end now.<br />';
          2.if not include php tags, the reusable.php source codes will be treated as plain HTML text
                reusable.php:  echo 'Here is a very simple PHP statement.<br />';
             then, codes will not be processed by php engine, finally print it out as it is.
                  <?php
                  echo 'This is the main file.<br />';
                 "echo 'Here is a very simple PHP statement.<br />;'"
                  echo 'The script will end now.<br />';
          3.include and require will parse the source codes, but readfile() echoes the content of a file without parsing it. this is safety precaution for user-provided text.
                  PHP is an interpreted language. This means that you will write code statements (lines of code)
                  and when a page is requested, the PHP interpreter will load your PHP code, parse it and then execute it. This differs from other languages,
                  such as Java or C#, where the source code is compiled and then executed. This is useful for web development in the fact that you do not have
                   to re-compile your source code for trivial code changes and the changes have immediate effect on all subsequent requests.
          4. if we change the auto_prepend_file and auto_append_file in php.ini, then every page will be automatically included the prepend file at the beginning of the page
                and automatically included append file in the end, this features will apply the effect to every page in the  document root
           */

//2. functions
            //1. parameters can be any type of php variable, including an array or object or even another function
            function funcName(){} // fuction names are not case sensitive but variables are case sensitive
            //2. fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource
                      //parameter inside [] is optional, we can leave out parameter from right but not from left
            //3. variable function
                function myPrintFunc (){
                    echo "hhhhhhha";
                }
                $name = 'myPrintFunc';
                $name(); // <=> myPrint();
            //4. $header and captions were optional, because they have default values,passing parameters must be from left to right
            function create_table($data, $header=NULL, $caption=NULL) {
                echo '<table>';
                if ($caption) {
                    echo "<caption>$caption</caption>";
                }
                if ($header) {
                    echo "<tr><th>$header</th></tr>";
                }
                reset($data);
                $value = current($data);
                while ($value) {
                    echo "<tr><td>$value</td></tr>\n";
                    $value = next($data);
                }
                echo '</table>';
                echo "Numbers of arguments:".func_num_args(); //3
                print_r(func_get_args()); //Returns an array comprising a function's argument list
                /*Array ( [0] => Array ( [0] => First piece of data [1] => Second piece of data [2] => And the third )
                           [1] => Data
                           [2] => Data about something ) */
                echo "the second parameter:".func_get_arg(1); // returns 2nd arguments of arguments list starting from 0
                //the second parameter:Data
            }

            $my_data = ['First piece of data','Second piece of data','And the third'];
            $my_header = 'Data';
            $my_caption = 'Data about something';
            create_table($my_data, $my_header, $my_caption);
            create_table($my_data);
            create_table($my_data, $my_header);
            create_table($my_data, NULL, $my_caption);
            //create_table($my_data,  $my_caption); wrong  my_caption value passes to header, this is not what we intended to do.
            echo '<hr>';

//3.understanding variable scope
            //1. local variable: variable inside the function, visible and usable inside the function, using global to declare it to global variable
            //2.global variable: variable outside the function, visible and usable in the whole script, but not inside the function
            //3.special superglobal variables: visible and usable both inside and outside functions
            function fn(){
                $var = "contents";  //local variable, valid inside function, invalid after fn call
                //global $var;  //if we use global to declare this variable's scope covers the whole script
                //$var= "contents";  //assign a value to global $var
            }
            fn();
            //trying to echo $var out in the fn(), wrong!
            echo $var; // this is a new global variable, has nothing to do with $var inside fn(), NULL will be printed
            //inverse from above example
            function func(){
                // echo  $var1; //trying to get $var1 from outside function, wrong
                 $var2 = 2;
                 echo  $var2; //2
                 //echo  $var1; // invisible inside function

            }
            $var1 = "contents";  //global variable by default
            func();
            echo  $var1; //$var1 is a global variable, correct! contents
            echo '<hr>';

//4.passing by reference versus passing by value
            //
            function increment1($value, $amount=1){
                $value += $amount;
            }
            function increment2( $value, $amount=2){
                global $value; //if global $value, then this $value is a new variable and will overwrite the local parameter to be passed
               //$value is NULL by default, this method can increment the parameter by calling,
                //but it must remain the same variable outside function, so let's username reference &
                //$value =100;
                $value += $amount;
            }
            function increment3(&$value, $amount=1){
                $value += $amount;
            }
            $a = 2;
            $b = 20;
            $c =200;
            increment1($a); //unchanged  still 2  //create double data 2, 2  then $value=2. independent each other
            increment2($b); // like above $b is unchanged, 2 is passed to $value,but $value is overwritten by global new $value which is NULL by default.
            increment3($c);  //changed  only one data 200, $c and $value points at the same data 200
            echo $a; //2
            echo $value; //2   $value += $amount;  $value = NULL +2 =2
            echo $b; //20
            echo $c; //201
            echo '<hr>';

//5. return
            //1.return to the statement after the function call even though execution of that function is not complete
            //2.return a value from functions
            //3.return false or NULL is not visible
            function larger($x,$y){
                if(isset($x) && isset($y)){ //Determine if a variable is created(NULL) and given a value
                    return $x > $y ?$x:$y;
                }else{
                    return false; //NULL and false are invisible
                }
            }
            echo larger(2,3); //3
            echo larger(2,NULL ); //false
            echo larger(-2,0); //0 equals to false but not fully equals to false
            echo larger(2,0) ===0; //true
            echo larger(2,NULL) ==0; //true (false == 0)
            echo larger(2,NULL) ===0; //false  (false !=== 0)

//6.recursion
            //recursive function are slower and use more memory than iteration, better use iteration
            function reverse_r($str) { //recursive, more elegant
                if (strlen($str)>0) {
                    reverse_r(substr($str, 1)); //second character to the last
                }
                echo substr($str, 0, 1);//brilliant, first character
                return;
            }

            function reverse_i($str) {  //iteration
                for ($i=1; $i<=strlen($str); $i++) {
                    echo substr($str, -$i, 1);
                }
                return;
            }
            reverse_r('Hello'); //olleH
            echo '<br />';
            reverse_i('Hello');//olleH

//7.Implementing Anonymous Functions(Closures)
            //closures(anonymous function ) is used as callbacks, that is, as functions that are passed to other functions
            // array_walk($arr,callable func[, mixed userData])
                        //applying any function to each element in a array. using array_walk($arr,callable func[, mixed userData])
                        // callable func is the  name of a user-defined function that applies the same change to every element.

                        function myPrint($value)  //adding & will change the $arr
                        {
                            echo "$value<br/>";
                        }
                        $arr =[2,3,4,5];
                        //1.this will not change the arr due to &,using  for looping the array, just like iteration
                        array_walk($arr, "myPrint");  //myPrint is the name of the function,
                        print_r($arr);
                        //2. anonymous function(closure )
                        array_walk($arr, function ($value){echo "$value<br/>";});
                        //3. assign closure to a variable, get a variable name to call this anonymous function
                        $printer = function ($value){echo "$value<br/>";}   ;  //remember there is a semicolon at end of the statement
                        $printer("hello");
                        $printer("123");
                        $printer(123);
                        array_walk($arr,$printer); //if only the second parameter is function name,to call a function without parenthesis
            //Example
                        $printer =  function($value){ echo "$value <br/>"; };

                        $products = [ 'Tires' => 100,
                            'Oil' => 10,
                            'Spark Plugs' => 4 ];

                        $markup = 0.20;

                        $apply = function(&$val) use ($markup) {
                            //because $markup is a global variable outside closure, but we want to use it inside closure,
                            // so we use " use ($markup)" to get access to $markup in the closure definition
                            $val = $val * (1+$markup); //here we can use $markup
                            $markup =$markup * 10; //this $markup is a new $markup that will overwrite the old one
                            // this $markup does not change the $markup outside closure
                            //better to use, worse to be assigned.
                        };

                        array_walk($products, $apply); //apply changes to every element's value due to & is used in the definition of closure.

                        array_walk($products, $printer); //iterate $product
                        echo $markup;   //still 0.2
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!