2011-07-04 58 views
3

我有以下问题PHP的面向对象的调用方法

class class_name { 

function b() { 
    // do something 
} 

function c() { 

    function a() { 
     // call function b(); 
    } 

} 

} 

当我打电话功能照常函数:$ this-> B();我得到这个错误:使用$这个时候不是在C对象方面:...

函数B()被声明为public

有什么想法?

我感谢所有帮助

感谢

回答

7

a()的内部方法c()声明的功能。 (不推荐)使用方法内部功能

<?php 

class class_name { 
    function b() { 
    echo 'test'; 
    } 

    function c() { 

    } 

    function a() { 
    $this->b(); 
    } 
} 

$c = new class_name; 
$c->a(); // Outputs "test" from the "echo 'test';" call above. 

之所以你原来的代码不工作是因为变量的范围。 $this仅在该类的实例中可用。函数a()不再是它的一部分,因此解决此问题的唯一方法是将实例作为变量传递给类。

<?php 

class class_name { 
    function b() { 
    echo 'test'; 
    } 

    function c() { 
    // This function belongs inside method "c". It accepts a single parameter which is meant to be an instance of "class_name". 
    function a($that) { 
     $that->b(); 
    } 

    // Call the "a" function and pass an instance of "$this" by reference. 
    a(&$this); 
    } 
} 

$c = new class_name; 
$c->c(); // Outputs "test" from the "echo 'test';" call above. 
+0

有没有办法从那里调用它? – user681982

+0

我想这是最好的做法...好吧我会让它成为你拥有的方式 – user681982

+0

感谢那 – user681982