note 72475 deleted from function.func-num-args by googleguy

From: Date: Tue, 22 Oct 2013 15:00:11 +0000
Subject: note 72475 deleted from function.func-num-args by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-197291@lists.php.net to get a copy of this message
Note Submitter: padron at aaargh dot com dot br ---- func_num_args(), func_get_args() and func_get_arg() can be very useful to emulate overloading in PHP. Suppose you have a class to add a user in a system, and that you want to allow 2 ways of doing it. The first way would be passing an array with all the user info in it, and the second way would be passing each user attribute as a single argument. <?php class Test { 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.<br/>"; echo "ID: " . $user["id"] . "<br/>"; echo "NAME: " . $user["name"] . "<br/>"; echo "EMAIL: " . $user["email"] . "<br/>"; } else { // generates an error if argument is not an array echo "Argument is not an array: " . $user . ".<br/>"; } } 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.<br/>"; echo "ID: " . func_get_arg(0) . "<br/>"; echo "NAME: " . func_get_arg(1) . "<br/>"; echo "EMAIL: " . func_get_arg(2) . "<br/>"; } else { // if the number of arguments is different from 1 and 3 // an error will be generated echo "Wrong argument number.<br/>"; 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 "<br/>"; // inserts an user providing each attribute as a single argument $objTest->insertUser(2, "Vicente Fox", "iloveusa@disney.com"); echo "<br/>"; // this will generate an error, because only 2 arguments were passed $objTest->insertUser(3, "Tony Blair"); ?>

« previous php.notes (#197291) next »