default argument values

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nikola Skoric

    default argument values

    Hi there, is something like this possible in PHP:

    function foo($a=1, $b=2, $c=3) {
    //...
    }

    foo($b=2);

    Will this assign $a and $c to default values?

    --
    "Now the storm has passed over me
    I'm left to drift on a dead calm sea
    And watch her forever through the cracks in the beams
    Nailed across the doorways of the bedrooms of my dreams"
  • Ksu

    #2
    Re: default argument values

    only
    function foo($b=2,$a=1, $c=3) {
    }

    foo(2);

    Comment

    • ZeldorBlat

      #3
      Re: default argument values


      Nikola Skoric wrote:[color=blue]
      > Hi there, is something like this possible in PHP:
      >
      > function foo($a=1, $b=2, $c=3) {
      > //...
      > }
      >
      > foo($b=2);
      >
      > Will this assign $a and $c to default values?
      >
      > --
      > "Now the storm has passed over me
      > I'm left to drift on a dead calm sea
      > And watch her forever through the cracks in the beams
      > Nailed across the doorways of the bedrooms of my dreams"[/color]

      Unfortunately it doesn't work that way. The default is only taken when
      the argument is not specified at all and I don't think you can name the
      parameters like that when you call the function. The best you can do
      is something like this:

      function foo($a = 1, $b = 2, $c = 3) {
      //do something
      }

      //Is valid, $a = 5, $b = 2, $c = 3
      foo(5);

      //Is valid, $a = 5, $b = 42, $c = 3
      foo(5, 42);

      //Syntactically valid, but results in $a = 5, $b = 2, and $c = 3
      inside the function.
      //Basically assign 5 to $b (outside the function) then pass the result
      (5) as the first
      //parameter to foo():
      foo($b = 5);

      Comment

      • Iván Sánchez Ortega

        #4
        Re: default argument values

        -----BEGIN PGP SIGNED MESSAGE-----
        Hash: SHA1

        Nikola Skoric wrote:
        [color=blue]
        > Hi there, is something like this possible in PHP:
        >
        > function foo($a=1, $b=2, $c=3) {
        > //...
        > }
        >
        > foo($b=2);
        >
        > Will this assign $a and $c to default values?[/color]

        No.

        - --
        - ----------------------------------
        Iván Sánchez Ortega -i-punto-sanchez--arroba-mirame-punto-net

        Give a man a fish, he owes you one fish.
        Teach a man to fish, you give up your monopoly on fisheries.
        (read on slashdot.org)
        -----BEGIN PGP SIGNATURE-----
        Version: GnuPG v1.4.2.2 (GNU/Linux)

        iD8DBQFEGeN73jc Q2mg3Pc8RAuzIAJ 9405fAxCU7dMY8G qi5gFiTepDoLwCf ZNqh
        hP+JeBrEfRAudgd 90HTy+YI=
        =CgWw
        -----END PGP SIGNATURE-----

        Comment

        Working...