SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2007
    Posts
    56
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Functions and Default Argument Values

    I have a function that is declared like that:
    PHP Code:
    function some_function($arg1 'default'$arg2 'default'
    How do I tell the function:
    - use your default value for your 1st argument;
    - use 'some specific value' for your 2nd argument;

    Something like:
    PHP Code:
    some_function([use default value], 'some specific value'

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You can't.

  3. #3
    SitePoint Enthusiast
    Join Date
    Feb 2007
    Posts
    56
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

  4. #4
    SitePoint Evangelist
    Join Date
    Jun 2006
    Location
    Wigan, Lancashire. UK
    Posts
    523
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've not tried it:
    PHP Code:
    function some_function($arg1 'default1'$arg2 'default2') {
       return 
    $arg1.' + '.$arg2;
    }
    $echo some_function(,'argument2'
    or does PHP pass in a null value for argument #1?

    If so, then you'd need something like:
    PHP Code:
    function some_function($arg1 'default1'$arg2 'default2') {
       if (
    is_null($arg1)) $arg1 'default1';
       if (
    is_null($arg2)) $arg2 'default2';
       return 
    $arg1.' + '.$arg2;

    ---
    Development Projects:
    PHPExcel
    PHPPowerPoint

  5. #5
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    No, that just won't run at all. You'll get a parse error.

  6. #6
    SitePoint Zealot zalucius's Avatar
    Join Date
    Jul 2007
    Location
    Denmark
    Posts
    162
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perhaps you should rethink how your function is constructed.
    if you sometimes have two arguments, and at othertimes have only one, then why not make two functions?

    Code PHP:
    <?php
    // takes one argument, and passes it to the other function as the second argument.
    function one_arg_function($arg = 'default')
    {
    	return two_args_function('default from "one arg" function', $arg);
    }
     
    function two_args_function($arg1 = 'default', $arg2 = 'default')
    {
    	//do something
    	return $arg1.$arg2;
    }
     
    echo one_arg_function('calling one arg function');
     
    echo two_arg_function('first at two arg function', 'second at two arg function'); 
    ?>
    zalucius

  7. #7
    SitePoint Enthusiast
    Join Date
    Feb 2007
    Posts
    56
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I can use something like:

    PHP Code:
    function do_something($arg1 null$arg2 'default')
    {
        if(!
    $arg1)
        {
            
    $arg1 'default';
        }

    ... and it would do the job. I was hoping a more elegant approach was available though.

  8. #8
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Elegant, it is not.
    PHP Code:
    <?php
    function doSomething()
    {
        
    $defaults = array(
            
    'name'    =>    'SilverBulletUK',
            
    'age'    =>    29
        
    );
        
        if(
    func_num_args() > 0)
        {
            
    $argument_index 0;
            foreach (
    $defaults as $key => $value)
            {
                if(
    func_num_args() >= ($argument_index 1))
                {
                    if(
    false === is_null(func_get_arg($argument_index)))
                    {
                        
    $defaults[$key] = func_get_arg($argument_index);
                    }
                }
                
    $argument_index++;
            }
        }
        
        
    extract($defaults);
        
        return 
    $name ' is ' $age;
    }

    echo 
    doSomething();            #SilverBulletUK is 29
    echo doSomething(null30);    #SilverBulletUK is 30
    echo doSomething('M40_');    #M40_ is 29
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  9. #9
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Hmmm, 2nd attempt.
    PHP Code:
    <?php
    function doSomething()
    {
        
    $default_args = array(
            
    0    =>    'SilverBulletUK',
            
    1    =>    29
        
    );
        
        if(
    func_num_args() > 0)
        {
            for(
    $index 0$index func_num_args(); $index++)
            {
                if(
    false === is_null(func_get_arg($index)))
                {
                    
    $default_args[$index] = func_get_arg($index);
                }
            }
        }
        
        list(
    $name$age) = $default_args;
        
        return 
    $name ' is ' $age;
    }

    echo 
    doSomething();            #SilverBulletUK is 29
    echo doSomething(null30);    #SilverBulletUK is 30
    echo doSomething('M40_');    #M40_ is 29
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  10. #10
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Ah, much better.
    PHP Code:
    <?php
    function silverbulletuk($age 29$weight 'chubby')
    {
        
    $function = new ReflectionFunction(__FUNCTION__);
        foreach (
    $function->getParameters() as $parameter)
        {
            if(
    true === is_null(${$parameter->name}))
            {
                ${
    $parameter->name} = $parameter->getDefaultValue();
            }
        }
        return 
    'SilverBulletUK is ' $age ' and ' $weight;
    }

    echo 
    silverbulletuk(null'slender');    #SilverBulletUK is 29 and slender
    echo silverbulletuk(30'slender');        #SilverBulletUK is 30 and slender
    echo silverbulletuk(30null);            #SilverBulletUK is 30 and chubby
    echo silverbulletuk();                    #SilverBulletUK is 29 and chubby
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  11. #11
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    A little bit of rework as it fell over on non-optional parameters.
    PHP Code:
    <?php
    function welcome_message($name$site 'Sitepoint.com'$level null)
    {
        
    $reflection_function = new ReflectionFunction(__FUNCTION__);
        foreach (
    $reflection_function->getParameters() as $function_parameter){
            if(
    true === $function_parameter->isOptional() && true === is_null(${$function_parameter->name})){
                ${
    $function_parameter->name} = $function_parameter->getDefaultValue();
            }
        }
        
        
    /**
         * Normal code resumes...
         */
        
    return sprintf(
            
    'Hi %s%s, welcome to %s!',
            
    $name,
            
    is_null($level) ? null '(' $level ')',
            
    $site
        
    );
    }

    echo 
    welcome_message('SilverBulletUK'nullnull);            #Hi SilverBulletUK, welcome to Sitepoint.com!
    echo welcome_message('SilverBulletUK'null'Member');        #Hi SilverBulletUK(Member), welcome to Sitepoint.com!
    echo welcome_message('SilverBulletUK''Google.com'null);    #Hi SilverBulletUK, welcome to Google.com!
    ?>
    Essentially, you just need to add the following 6 lines of code to any function. This will allow you to pass null to any optional parameter and it will revert the parameter back to its default.
    PHP Code:
        $reflection_function = new ReflectionFunction(__FUNCTION__);
        foreach (
    $reflection_function->getParameters() as $function_parameter){
            if(
    true === $function_parameter->isOptional() && true === is_null(${$function_parameter->name})){
                ${
    $function_parameter->name} = $function_parameter->getDefaultValue();
            }
        } 
    I've enjoyed this.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  12. #12
    SitePoint Enthusiast
    Join Date
    Feb 2007
    Posts
    56
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Haha Nice progression. Thanks for the code!

  13. #13
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Yeah, I thought so too. Your most welcome.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  14. #14
    Floridiot joebert's Avatar
    Join Date
    Mar 2004
    Location
    Kenneth City, FL
    Posts
    823
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    <?php

    class fun_args
    {
        public 
    $a$b$c;
        public function 
    __construct()
        {
            
    $this->'a';
            
    $this->'b';
            
    $this->'c';
        }
    }

    function 
    fun(fun_args $a)
    {
        echo 
    "{$a->a} {$a->b} {$a->c}";
    }

    $instance = new fun_args();
    $instance->'giant';
    $instance->'peach';

    fun($instance);

    ?>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •