Passing *optionally* by-reference in PHP4 ??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Passing *optionally* by-reference in PHP4 ??

Post by Chris Corbyn »

Code: Select all

<?php

error_reporting(E_ALL);

class foo
{
        var $property;

        function foo(&$item=false)
        {
                $this->property =& $item;
                $this->fill();
        }

        function fill()
        {
                $this->property = array(1, 2, 3);
        }
}

$obj =& new foo($bar);

print_r($bar);

?>
This works fine in PHP5. In PHP4 I get:

Code: Select all

Parse error: parse error, unexpected '=', expecting ')' in /home/d11wtq/public_html/foo.php on line 9
Seems if I leave off the "=false" part it works, but without it it becomes a required paramater :(
namitjung
Forum Commoner
Posts: 42
Joined: Mon Jun 20, 2005 3:17 am

about php 4

Post by namitjung »

You are passing the value by referene with default parameter. I don't think that php 4 will support this type of syntax at all. About php 5, i can't say anything coz i didn't use it yet.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

use arrays ?

Code: Select all

function foo($bar = false)
{
  if ($bar !== false and is_array($bar))
  {
    $this->property =& $bar[0];
  }
}


$cheese = 'yes';

foo(array(&$cheese));
or

Code: Select all

function foo()
{
  $this->property = (func_num_args() > 0 ? &func_get_arg(0) : false);
}
I haven't tried that before, but may work in some fashion.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

feyd wrote:use arrays ?

Code: Select all

function foo($bar = false)
{
  if ($bar !== false and is_array($bar))
  {
    $this->property =& $bar[0];
  }
}


$cheese = 'yes';

foo(array(&$cheese));
or

Code: Select all

function foo()
{
  $this->property = (func_num_args() > 0 ? &func_get_arg(0) : false);
}
I haven't tried that before, but may work in some fashion.
I'll give it a shot.... it doesn't really have the same effect though :(

Cheers buddy :)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Hmm... doesn't work :( I'm starting to think this is not possible in PHP4... shame. I'll have to make the API for my PHP4 version of something I'm doing a bit more restrictive. I'm open to other suggestions though :)
Post Reply