Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - can a method return a pointer?

Tags:

php

pointers

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?

like image 738
Kerry Jones Avatar asked Jun 02 '10 23:06

Kerry Jones


1 Answers

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

like image 115
johannes Avatar answered Sep 24 '22 04:09

johannes