簡體   English   中英

無法破解OOP PHP鏈接類->屬性->方法

[英]Cant crack OOP PHP chaining class->property->method

經過數小時的嘗試和失敗后,我在這里尋求任何我能得到的幫助。 我相信對於熟悉 OOP 的人來說這很簡單,但我只是找不到任何文檔來幫助我解決這個問題,並且我自己也無法解決它。

我有無法更改的代碼: $woocommerce_wpml->multi_currency->get_currency_codes(); 我需要為它創建一個類,以便它返回我選擇的值。

我知道您可以創建類 ($woocommerce_wpml = new xyClass;) 並獲取其屬性 ($woocommerce_wpml->multi_currency)。

我知道您可以在該類中創建方法並運行它($woocommerce_wpml->get_currency_codes();)

我知道你可以鏈接方法,但我就是不知道如何鏈接類->屬性->方法。 或者它不是財產,我看錯了?

$woocommerce_wpml 是類嗎? multi_currency 應該是財產權嗎? get_currency_codes() 是正確的方法嗎?

我如何鏈接這些(類->屬性->方法)?

我失敗的代碼:

class testClass {
  public $multi_currency;
    function __construct($multi_currency) {
      $this->multi_currency = $multi_currency;
    }

  public function get_currency_codes() {
      return $this->multi_currency;
    }

}

$woocommerce_wpml = new testClass(["CZK","EUR"]);

var_dump( $woocommerce_wpml->multi_currency); //array(2) { [0]=> string(3) "CZK" [1]=> string(3) "EUR" } 
var_dump($woocommerce_wpml->get_currency_codes()); //array(2) { [0]=> string(3) "CZK" [1]=> string(3) "EUR" }
echo $woocommerce_wpml->multi_currency->get_currency_codes(); //Fatal error: Uncaught Error: Call to a member function get_currency_codes() on array in ...

對象屬性可以是對對象的引用。


$myclass->property = new OtherClass();

echo $myclass->property->other_class_property;

//or access method 
$myclass->property->other_class_method();

暫無
暫無

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

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