相关疑难解决方法(0)

如何在PHP 5中通过引用传递对象?

在PHP 5中,您是否需要使用&修饰符通过引用传递?例如,

class People() { }
$p = new People();
function one($a) { $a = null; }
function two(&$a) { $a = null; )
Run Code Online (Sandbox Code Playgroud)

在PHP4中,您需要&修改器在进行更改后维护引用,但是我对我读过的关于PHP5自动使用pass-by-reference的主题感到困惑,除非明确克隆对象.

在PHP5中,是否 & 需要通过引用传递所有类型的对象(变量,类,数组......)?

php variables object pass-by-reference

22
推荐指数
1
解决办法
3万
查看次数

PHP中的对象是通过值还是引用传递的?

在这段代码中:

<?php
class Foo
{
    var $value;

    function foo($value)
    {
        $this->setValue($value);
    }

    function setValue($value)
    {
        $this->value=$value;
    }
}

class Bar
{
    var $foos=array();

    function Bar()
    {
        for ($x=1; $x<=10; $x++)
        {
            $this->foos[$x]=new Foo("Foo # $x");
        }
    }

    function getFoo($index)
    {
        return $this->foos[$index];
    }

    function test()
    {
        $testFoo=$this->getFoo(5);
        $testFoo->setValue("My value has now changed");
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

当该方法Bar::test()运行并且它改变了foo对象数组中foo#5的值时,数组中的实际foo#5是否会受到影响,或者该$testFoo变量只是一个最终不再存在的局部变量功能?

php oop

19
推荐指数
3
解决办法
2万
查看次数

函数内部的静态变量不能保持对单例的引用

我已经注意到PHP中单例的奇怪行为,没有更好的方法来解释这个但是举个例子.

假设我有以下单例类:

class Singleton
{
    protected function __construct()
    {
        // Deny direct instantion!
    }
    protected function __clone()
    {
        // Deny cloning!
    }
    public static function &Instance()
    {
        static $Instance;

        echo 'Class Echo'.PHP_EOL;
        var_dump($Instance);

        if (!isset($Instance)) {
            $Instance = new self;
        }

        return $Instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

并具有以下功能:

function Test($Init = FALSE)
{
    static $Instance;

    if ($Init === TRUE && !isset($Instance)) {
        $Instance =& Singleton::Instance();
    }

    echo 'Function Echo'.PHP_EOL;
    var_dump($Instance);

    return $Instance;
}
Run Code Online (Sandbox Code Playgroud)

当我使用以下内容时:

Test(TRUE);
Test();
Singleton::Instance();
Run Code Online (Sandbox Code Playgroud)

输出是:

Class Echo
NULL
Function …
Run Code Online (Sandbox Code Playgroud)

php singleton static reference function

4
推荐指数
1
解决办法
1214
查看次数