Home > Backend Development > PHP Tutorial > PHP 函数引用

PHP 函数引用

WBOY
Release: 2016-06-23 13:19:45
Original
1401 people have browsed it

function &referenceFunc() {    static $foo = '';    return $foo;        }//将静态变量$foo的引用传递给$name$bar = &referenceFunc();$bar .= "hello";//作为普通函数调用echo referenceFunc();//删掉引用unset($bar);//作为普通函数调用$bar = referenceFunc();$bar .= " world";//$foo并不会发生变化echo referenceFunc();
Copy after login

PHP的函数引用是将函数返回值的引用返回给接收变量,函数声明or调用时都需要使用取值运算符 &,但调用时也可以作为普通函数直接使用(此时便没有的函数引用的特性,接收变量会在指向内存新的地址),其他的还有参数引用(值传递/引用传递),对象引用

突破类封装

class Reference {    private $foo;    public function &referenceFoo() {        return $this->foo;    }        public function getFoo() {        echo $this->foo . "<br>";    }}$obj = new Reference();//将私有变量绑定在了一个普通变量$bar上$bar = &$obj->referenceFoo();//外部操作私有变量$bar .= "access the private var in outside";//输出'access the private var in outside'$obj->getFoo();
Copy after login

当然函数引用不是用来做这些事情的,函数引用主要用处是让你可以为当前对象的某一属性绑定一个额外的别名方便操作

注意定义或调用时都要使用 "&" 运算符,否则则是作为普通函数or方法调用

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template