Jump to content

PHP's Lack of Pointers


neoform

Recommended Posts

I've run into a problem which I don't think can be solved since php only has references and does not have pointers..

 

$GLOBALS['glob_var'] = 10;

funk($var);
echo 'SHOULD BE 10: '.$var.'<br />\n';

function funk(&$ref_var)
{
$ref_var = &$GLOBALS['glob_var'];
echo 'SHOULD BE 10: '.$ref_var.'<br />\n';
}

 

This outputs:

 

SHOULD BE 10: 10
SHOULD BE 10: 

 

Any ideas on how to fix this without duplicating the contents of $GLOBALS['glob_var'] ?

 

Link to comment
https://forums.phpfreaks.com/topic/100802-phps-lack-of-pointers/
Share on other sites

with global-ized variables or super globals like $GLOBALS it isn't necessary to reference them within a function, ex

 

$my_var = 12345;
echo $my_var;

function afunc() {
global $my_var;
$my_var = 23456;
}

afunc();

echo '<br />'.$my_var;

 

would output

 

12345

23456

 

References are useful when passing variables to functions and you want to modify them, ex:

 

$my_var = 12345;
echo $my_var;

function afunc(&$ref_to_my_var) {
$ref_to_my_var = 23456;
}

afunc($my_var);

echo '<br />'.$my_var;

 

will output

 

12345

23456

I'm using this purely as an example, my real code involves class member variables and they aren't integers, they're objects..  i just used this example to simplify it.

 

realistically, i want to pass a reference to the object without duplicating it (which would use up a lot more memory).

 

Maybe I wasn't clear enough before, I'm looking to pass back a reference..  this should work, but doesn't.

 

 

$GLOBALS['glob_var'] = 10;

funk($var);
echo 'SHOULD BE 10: '.$var."<br />\n";
$GLOBALS['glob_var'] = 11;
echo 'SHOULD BE 11: '.$var."<br />\n";

function funk(&$ref_var)
{
$ref_var = &$GLOBALS['glob_var'];
echo 'SHOULD BE 10: '.$ref_var."<br />\n";
}

That's more along the line of what I'm trying to do, but this still gives a copy of the var, not a reference :(

 

$GLOBALS['glob_var'] = 10;

$var = & funk();
echo 'SHOULD BE 10: '.$var."<br />\n";
$GLOBALS['glob_var'] = 11;
echo 'SHOULD BE 11: '.$var."<br />\n";

function funk()
{
return $GLOBALS['glob_var'];
}

 

SHOULD BE 10: 10
SHOULD BE 11: 10

<?php

$glob_var = 10;

funk($var);
echo 'SHOULD BE 10: '.$var."<br />\n";

function funk(&$ref_var)
{
$ref_var &= $GLOBALS['glob_var'];
echo 'SHOULD BE 10: '.$ref_var."<br />\n";
}

?>

 

Try that :)

 

BTW - need double quotes to parse \n as linebreak.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.