0

I've a php function ,

func($c) {

global $a,$b;

//Do something

}

I call it like this,

$c = "Test";
func($c);

But in some cases I need to pass an extra parameter $b and it should not be overridden by the global variable value so i tried this,

func($c,$b = $b,$a = $a) {

//Do something

}

But in PHP setting variable as default is not permitted. So kindly help me here ...

2
  • I don't get your question? Please elaborate what you wish to do or achieve? Commented Oct 5, 2011 at 9:33
  • That code you posted is not even valid PHP code.... Besides that, global variables are usually bad. Commented Oct 5, 2011 at 9:35

3 Answers 3

3

So you want to use a global var as the default value of a function argument? You can use the following code assuming null is never passed as a valid argument.

function func($c, $b = null, $a = null) {
    if($b === null) $b = $GLOBALS['b'];
    if($a === null) $a = $GLOBALS['b'];
}
Sign up to request clarification or add additional context in comments.

Comments

2

use func_get_args

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);
?>

Comments

0

May that will help you.

<?php

    function doWork($options)
    {
        extract(
            merge_array(
                array(
                    'option_1' => default_value,
                    'option_2' => default_value,
                    'option_3' => default_value,
                    'option_x' => default_value
                ),
                $options
            )
        );

        echo $option_1; // Or do what ever you like with option_1
    }

    $opts = array(
        'option_1' => custom_value,
        'option_3' => another_custom_value
    );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.