簡體   English   中英

從其他類調用函數

[英]Calling a function from a different class

我正在嘗試解決此問題,但我不能。 我認為我不正確地調用了該函數。 我也想知道Custom :: generate($ r1,$ p1,$ a1)與Custom :: generate之間的區別。

有趣的是我有這段代碼$c = $this->install(); 在同一個文件中,但功能不同,並且可以正常工作。 我感到困惑。 請幫助如何解決此錯誤

Custom.php:

class Custom {
  private function install() { 
  // code
  }

 public function generate($r1, $p1, $a1) {

 // code
 $c = $this->install();

 }
}

MotherUpdate.php

protected function exeGen() {

$template = Custom::generate($r1, $p1, $a1);

}

我收到此錯誤:

Fatal error: Uncaught Error: Using $this when not in object context in /Users/amin/Custom/Custom.php:12

根據我的評論,

generate()不是靜態函數。 您需要在訪問generate()函數之前實例化Custom()類。

您可以使用:例如訪問靜態函數。 Custom::function()

您應該做的是實例化Custom()類,然后調用generate()函數

protected function exeGen() {
//instantiate Custom Class
$custom = new Custom();
$template = $custom->generate($r1, $p1, $a1);    
}

同樣,在使用靜態函數時,不應在其內部使用$this

你需要這個

class Custom {
    public static function generate($r1, $p1, $a1) {
        // You can't use $this here
    }
}

$template = Custom::generate($r1, $p1, $a1);

或這個

class Custom {
    public function generate($r1, $p1, $a1) {
        // You can use $this here
    }
}


$custom = new Custom();
$template = $custom->generate($r1, $p1, $a1);

暫無
暫無

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

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