PHP Refresher

Functions

  • Always use descriptive function names.
  • PHP doesn’t support function overloading!
  • Functions are case-insensitive (but its good practice to use the declared name when invoking).
  • All PHP functions and classes have global scope. They can be called from outside the function even if they were defined inside and vice versa. Have a look at the code below to understand this!
function test(){

    echo 'test';

    function testInner(){
	echo 'test inner';
    }
}
test(); // if you don't call it before calling testInner(), you will get an error.
testInner();
  • You can pass arguments by value, or by reference, or default argument values.
  • Variable arguments:
function sum(...$args) {
    echo gettype( $args ); // array!
    // you can loop through array items using 'foreach' 
    foreach ($args as $arg) {
        // process argument here.
    }
}
sum( 1, 3, 4 );
sum(1, , 4, 5, 23, 5 );

// in older version of php, you can do above like:
function sum(){
    foreach (func_get_args() as $arg) {
        // process arg here.
    }
}
sum( 1, 3, 4 );
sum(1, , 4, 5, 23, 5 );
  • It is possible to declare the type of argument, a function receives. And once declared, if you don’t supply exact type, you will get an error.
function test( int $a, string $b ){
    var_dump( $a );
    var_dump( $b );
}
test( 1, 'name' ); // no error
test( null, 1 ); // fetal error

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.