Page 1 of 1

Passing *optionally* by-reference in PHP4 ??

Posted: Sun Mar 05, 2006 6:42 pm
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 :(

about php 4

Posted: Sun Mar 05, 2006 10:36 pm
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.

Posted: Sun Mar 05, 2006 11:13 pm
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.

Posted: Mon Mar 06, 2006 5:27 am
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 :)

Posted: Mon Mar 06, 2006 7:05 am
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 :)