2014-01-15 92 views
1

假设我想通过函数参数发送效果,我是否也可以通过该函数发送附加参数,不能真正解释它,下面是我将如何想象一下。PHP通过函数参数发送附加(可选)参数

<?php 
//Apply photo effects 
function applyEffect($url,$effect) { 
    //List valid effects first 


    $img = imagecreatefromjpeg($url); 

    //Testing 
    if($img && imagefilter($img, $effect)) { 
     header('Content-Type: image/jpeg'); 
     imagejpeg($img); 

     imagedestroy($img); 
    } else { 
     return false; 
    } 
} 

applyEffect("http://localhost:1234/ppa/data/images/18112013/0/image3.jpg",IMG_FILTER_BRIGHTNESS[20]); 
?> 

正如你可以看到我通过IMG_FILTER_BRIGHTNESS通过函数的参数,但我使用需要的筛选当我打电话的applyEffect功能,像这样它会是不错的附加参数发送:IMG_FILTER_BRIGHTNESS [20 ]

但是这不起作用,任何指针?

+0

这真的是相同数目的字符两种方式。您不妨使用逗号并正常传递它。实际上,如果你不使用空格,那么用逗号就少了。 – m59

+0

但是后来我不得不这样命名函数:'function applyEffect($ url,$ effect,$ arg1,$ arg2,$ arg3){' –

+0

但是现在作为额外的参数没有价值,除非他们需要一个错误抛出.. –

回答

2

这听起来像你想func_get_args然后你可以创建下一个函数调用的参数,并使用它像call_user_func_array(theFunction, $args)

function applyEffect($url, $effect, $vals) { 
    $img = makeImage($url); 

    //get an array of arguments passed in 
    $args = func_get_args(); 

    //update the first item with the changed value 
    $args[0] = $img; 

    //get rid of the 3rd item, we're about to add on its contents directly to $args array 
    unset($args[2]); 

    //add all the optional arguments to the end of the $args array 
    $args = array_merge($args, $vals); 

    //pass the new args argument to the function call 
    call_user_func_array(imagefilter, $args); 
} 

applyEffect('foo.jpg', 'DO_STUFF', array(20,40,90)); 


function imageFilter() { 
    $args = func_get_args(); 
    foreach ($args as $arg) { 
    echo $arg.'<br>'; 
    } 
} 

function makeImage($url) { 
    return "This is an image."; 
} 

您还可以在功能设置默认参数值是这样的:

function foo($arg1, $arg2=null, $arg3=null) { }

+0

谢谢!完美的作品 –

+0

@MartynLeeBall我更新了第一个解决方案。你也可能对此感兴趣。它可以让你传递你想要的许多值,并且最终的函数将被全部调用。 – m59