PHP Functions Accessing Function Parameters - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Functions Accessing Function Parameters - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, May 22, 2019

PHP Functions Accessing Function Parameters

PHP Functions




Accessing Function Parameters


Problem

You want to access the values passed to a function.

Solution

Use the names from the function prototype:

          function commercial_sponsorship($letter, $number) {
                  print "This episode of Sesame Street is brought to you by ";
                  print "the letter $letter and number $number.\n";
          }

          commercial_sponsorship('G', 3);

          $another_letter = 'X';
          $another_number = 15;
          commercial_sponsorship($another_letter, $another_number);

Discussion

Inside the function, it doesn’t matter whether the values are passed in as strings, numbers, arrays, or another kind of variable. You can treat them all the same and refer to them using the names from the prototype.

Unless otherwise specified, all non-object values being passed into and out of a function are passed by value, not by reference. (By default, objects are passed by reference.) This means PHP makes a copy of the value and provides you with that copy to access and manipulate. Therefore, any changes you make to your copy don’t alter the original value. For example:

          function add_one($number) {
          $number++;
          }

          $number = 1;
          add_one($number);
          print $number;

prints:

          1

If the variable had been passed by reference, the value of $number in the global scope would have been 2.

In many languages, passing variables by reference has the additional benefit of being significantly faster than passing them by value. Although passing by reference is faster in PHP, the speed difference is marginal. For that reason, we suggest passing variables by reference only when actually necessary and never as a performance-enhancing trick.


No comments:

Post a Comment

Post Top Ad