簡體   English   中英

如何在同一個類的另一個方法中調用一個方法?

[英]How can I call a method in another method in the same class?

我想知道是否可以從同一類中的另一個方法中調用一個方法嗎?

例如,此代碼非常簡單,有一個方法method_foo() ,它調用方法a()

<?php

    class foo {

        function a() {
            return 3;
        }

        function method_foo() {
            echo a();
        }
    }

    $obj = new foo();
    $obj->method_foo();

?>

但是當我調用method_foo() ,我收到此錯誤:

(!)致命錯誤:在線上/ home / guest / public_html / ...中調用未定義的函數a()
#時間記憶功能位置1 0.0015 312032 {main}()../index.html:0 2 0.0156 523056 foo-> method_foo()../index.html:1667

為什么會出現此錯誤? 我可以使這個例子工作嗎?

您需要使用$ this來訪問此方法。

class foo {

    function a()
    {
        return 3;
    }

    function __construct()
    {

    }

    function method_foo()
    {
        echo $this->a();
    }
}

$obj = new foo();
$obj->method_foo();

您應該像這樣在函數method_foo()中調用方法a():

echo $this->a(); //this will output 3

您可以在http://php.net/manual/en/ref.classobj.php上閱讀有關此內容的更多信息。

您可以使用$this調用相同的類方法/變量

 function method_foo()
 {
    echo $this->a();
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM