7

I have a method in a class trying to return a pointer:

<?php
public function prepare( $query ) {
    // bla bla bla

    return &$this->statement;
}
?>

But it produces the following error:

Parse error: syntax error, unexpected '&' in /home/realst34/public_html/s98_fw/classes/sql.php on line 246

This code, however, works:

<?php
public function prepare( $query ) {
    // bla bla bla

    $statement = &$this->statement;
    return $statement;
}
?>

Is this just the nature of PHP or am I doing something wrong?

1
  • 2
    He uses "public" so it's 5. And PHP 4 is dead dead dead. Commented Jun 3, 2010 at 0:05

1 Answer 1

14

PHP doesn't have pointers. PHP has reference. A reference in PHP is a true alias. But you don'tneed them. Objects are passed by handle (so they feel like references) for other data PHP uses a copy-on-write mechanism so there is no memory/performance penalty. The performance penalty comes when using references as they disable copy-on-write and therefore all the optimizations in the engine.

If you really want to return a reference youhave todeclare it in the signature:

public function &prepare( $query ) {
   // bla bla bla

   return $this->statement;
}

But as said: If $this->statement is an object there is no need.

See also http://php.net/references

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I'll definitely have to look into the difference of pointers/references/aliases etc. I'll just return the object (it is an object).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.