[ create a new paste ] login | about

Link: http://codepad.org/WbyaxyCj    [ raw code | output | fork ]

balajimca - PHP, pasted on Apr 2:
<?php

class Teste {

    function insertUser() {

        // gets the number of parameters
        $numArgs = func_num_args();
        
        // make decisions based on the arguments number
        if ($numArgs == 1) {
            // if it's only one argument, we suppose that it is an array with user info
            
            // gets the first argument
            $user = func_get_arg(0);
            
            // checks if it really is an array
            if (is_array($user)) {
                
                // here you should check if the array contains all necessary fields
                
                // adds the user
                echo "User added.\n";
                echo "ID: " . $user["id"] . "\n";
                echo "NAME: " . $user["name"] . "\n";
                echo "EMAIL: " . $user["email"] . "\n";
                
            } else {
                
                // generates an error if argument is not an array
                echo "Argument is not an array: " . $user . ".\n";
                
            }
            
        } else if ($numArgs == 3) {
            // if the function receives 3 arguments, we assume that they
            // are 'id', 'name' and 'email' respectively
            
            // inserts the user into the system
            echo "User added.\n";
            echo "ID: " . func_get_arg(0) . "\n";
            echo "NAME: " . func_get_arg(1) . "\n";
            echo "EMAIL: " . func_get_arg(2) . "\n";
                        
        } else {
            
            // if the number of arguments is different from 1 and 3
            // an error will be generated
            
            echo "Wrong argument number.\n ";
            echo "Arguments received: " . func_num_args();
            
        }
    }

}

// creates an Test object
$objTest = new Teste();

// inserts an user passing an array with all his info
$objTest->insertUser(array("id" => 1, "name" => "George W. Bush", "email" => "jackass@whitehouse.gov"));

echo "\n";

// inserts an user providing each attribute as a single argument
$objTest->insertUser(2, "Vicente Fox", "iloveusa@disney.com");

echo "\n";

// this will generate an error, because only 2 arguments were passed
$objTest->insertUser(3, "Tony Blair");

?>


Output:
1
2
3
4
5
6
7
8
9
10
11
12
User added.
ID: 1
NAME: George W. Bush
EMAIL: jackass@whitehouse.gov

User added.
ID: 2
NAME: Vicente Fox
EMAIL: iloveusa@disney.com

Wrong argument number.
 Arguments received: 2


Create a new paste based on this one


Comments: