【问题标题】:Cant crack OOP PHP chaining class->property->method无法破解OOP PHP链接类->属性->方法
【发布时间】:2020-09-19 18:21:05
【问题描述】:

经过数小时的尝试和失败后,我在这里寻求任何可以得到的帮助。我相信对于熟悉 OOP 的人来说这很简单,但我只是找不到任何文档来帮助我解决这个问题并且我自己无法解决它。

我有无法更改的代码:$woocommerce_wpml->multi_currency->get_currency_codes(); 我需要为它创建一个类,以便它返回我选择的值。

我知道你可以创建类 ($woocommerce_wpml = new xyClass;) 并获取它的属性 ($woocommerce_wpml->multi_currency)。

我知道您可以在该类中创建方法并运行它 ($woocommerce_wpml->get_currency_codes();)

我知道你可以链接方法,但我就是不知道如何链接 class->property->method。或者它不是一个属性,我看错了?

$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 ...

【问题讨论】:

  • 下面@Wakeel 的回答应该可以帮助你理解结构,也就是说,你为什么认为你need to create a class for it so it returns value of my choosing?如果我们能更好地了解您的用法,我敢打赌我们会提出更合适的解决方案。用不同的对象替换 $woocommerce_wpml->multi_currency 可能比 get_currency_codes() 返回的效果更多,除非你做得正确。
  • 我有一个 in wordpress 插件,用于检查特定类(其他插件依赖项),如果该类存在,它会要求 $woocommerce_wpml->multi_currency->get_currency_codes() 。现在我没有第二个插件,我需要向第一个插件提供这些参数(假类存在 + 属性)以启用它的某些功能
  • 很公平,希望它不需要来自缺少的插件的任何其他逻辑,如果不需要,那有点可行。一般来说,我倾向于添加缺少的插件或删除对它的依赖。添加自定义类作为multi_currency 现在或以后可能会导致意外行为。想象一下,如果稍​​后您添加另一个插件,该插件也检查$woocommerce_wpml->multi_currency 是否存在并看到它,然后尝试调用$woocommerce_wpml->multi_currency->get_some_other_thing(),这将引发致命错误。无论如何要考虑的事情,快乐的编码:)

标签: php oop


【解决方案1】:

对象属性可以是对对象的引用。


$myclass->propery = new OtherClass();

echo $myclass->property->other_class_property;

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

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多