PROGRAMMING

  minte9
MEMORYApp




S R Q
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Variable Scope

You can create a function that accepts a variable number of arguments.
 
/**
 * PHP has three variable scopes: 
 * global scope, function scope, class scope
 * 
 * A function accepts a variable numbers of arguments.
 * A coommon example is the printf() family of functions.
 */

function sumOfInts(int ...$ints)
{
    return array_sum($ints);
}

echo sumOfInts(1, 2, 3); // 6
echo sumOfInts(1, 2, 3, 4, 5); // 15

echo sprintf("%s %s is %d old", "John", "Smith", 10); 
    // John Smith is 10 old

Lists count

PHP provides three built-in functions to handle variable-length argument lists.
 
/**
 * PHP provides three built-in functions ...
 * to handle variable-length argument lists:
 * func_num_args(), func_get_arg(), func_get_args()
 *
 * Keep in mind that variable-length argument lists ...
 * are full of potential pitfalls.
 * 
 * While they are very powerful, ...
 * they do tend to make your code confusing.
 */

function myArray() 
{
    $arr = array(); $i = 0;

    if (func_num_args() == 0) {
        $arr[] = "Hello World";
    }

    if (func_num_args() > 0) {
        while($i < func_num_args()) {
            $arr[] = "Hello " . func_get_arg($i++);
        }
    }

    return $arr;
}

print_r(myArray()); // [Hello World]
print_r(myArray("John", "Mary")); // [Hello John, Hello Mary]

Questions    
Last update: 29 days ago
Basics