PHP通过函数参数发送附加(可选)参数

时间:2014-01-15 02:29:50

标签: 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]

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

1 个答案:

答案 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) { }

相关问题