在外部函数调用后获取对象

时间:2013-09-07 13:21:14

标签: php

如何在外部类实例调用之后调用对象上的函数而不使用静态类。

这是我的样本(它应该回应“OKAY!”):

class class1  {
    function func1()  {
        func3();          // function outside class
    }

    function func2()  {
        echo "AY!";
    }
}

$foo = new class1();
$foo->func1();

function func3()
{
    echo "OK";
    $foo->func2();       // class instance doesn't exist any more
}

2 个答案:

答案 0 :(得分:4)

class class1  {
    function func1()  {
        func3($this);          // function outside class
    }

    function func2()  {
        echo "AY!";
    }
}

$foo = new class1();
$foo->func1();

function func3($object)
{
    echo "OK";
    $object->func2();       // class instance doesn't exist any more
}

答案 1 :(得分:0)

实例传递为参数。按照代码

<?php

class class1  {
    function func1($foo)  {
        func3($foo);          // function outside class
    }

    function func2()  {
        echo "AY!";
    }
}

$foo = new class1();
$foo->func1($foo);

function func3($foo)
{
    echo "OK";
    $foo->func2();       // class instance doesn't exist any more
}
?>

输出:

OKAY!