View Single Post
Old 11-27-2007, 08:38 AM   #1 (permalink)
Gibou
The Contributor
 
Gibou's Avatar
 
Join Date: Nov 2007
Location: France, near Paris
Posts: 53
Thanks: 6
Gibou is on a distinguished road
Terminal When PHP tries to imitate C

Hi !

I have been impressed by this topic where Wildhoney gives a fantastic use of the __call magic method and it gave me the idea to propose mine. Don't hesitate to criticize :)

If someone here knows the C development, you have certainly heard about va_list. it's this kind of functions which can take as many parameters as you want.

For instance, in C, the first function you learn (printf) is a va_list. Indeed, you can give to it a string and after, as many parameters you have defined in the first string.

The prototype of a such function is : "int printf (const char *format, ...);"

The goal is to do the same in PHP with __call

For instance, an easy example, you want to do this kind of operation :

PHP Code:
$op->add(1,2,3);
// but too :
$op->add(1,2,3,4,5,6); 
To do that, you have to declare two differents method or to give an array of values in parameter and it's not very easy to read.

I propose this (in a class "Operation")

PHP Code:
public function __call($method$args null)
{
    if(
$args)
    {
        
// Initiation of the allowed methods
        
$possibleOps = Array(
        
"add" =>
        Array(
"method" => "addition""init" => 0),
        
"sub" =>
        Array(
"method" => "substract""init" => $args[0]*2),
        
"mul" =>
        Array(
"method" => "multiplicate""init" => 1),
        
"div" =>
        Array(
"method" => "divide""init" => pow($args[0],2))
        );

        
// If the called method is allowed...
        
if(in_array($method,$possibleOps) && sizeof($args) >= 2)
        {
            
// Selection of the method
            
$tools $possibleOps($method);
            
// Initiation of the temporary value
            
$tmp $tools["init"];
            
// Operations
            
foreach($args as $val)
                
$tmp $this->$tools["method"]($tmp,$val);
            unset(
$tools);
            unset(
$possibleOps);
            return(
$tmp);
        }
        else
            return 
"Method not allowed";
    }
}

// Tests
$op = new Operation();
echo 
$op->add(1,2,3,4,5)."<br />";
echo 
$op->sub(5,4)."<br />";
echo 
$op->mul(2,5,3)."<br />";
echo 
$op->div(40,4,5); 
Perhaps a little too heavy.
I confess I haven't tested it yet. Like we say in french, "à vue de nez, c'est bon" :D

What do you think of the concept ? I ask myself if the regulars accesses to the private methods don't burden the code in ram.
__________________
Wedus project's Website
Send a message via MSN to Gibou
Gibou is offline  
Reply With Quote