【问题标题】:Return the values from each method into an object array将每个方法的值返回到对象数组中
【发布时间】:2021-03-10 15:18:28
【问题描述】:

学习 php OOP...

我需要两个方法($theme 和 $panel)的值来替换 Foo 和 Bar。

我正在尝试返回一个包含 $theme 和 $panel 的单个对象数组,其中一次调用了 Test 类。

class Test {
        
    public $parent_theme_settings;
    public $admin_panel_settings;
    
    public function __construct() {     
        $this->parent_theme_settings = 'foo';       
        $this->admin_panel_settings = 'bar';
    }   
    
    public function parent_theme_settings() {       
        $theme = file_get_contents( plugin_dir_path( dirname( __FILE__ ) ) . 'includes/parent-theme-config.json' );     
        return $theme;      
    }

    public function admin_panel_settings() {
        $panel = get_option( 'settings_panel' );                
        return $panel;
    }

}
$FooBar = new Test();

【问题讨论】:

  • 欢迎来到 SO!你试过$FooBar->functionname(),即$FooBar->parent_theme_settings()吗?
  • “我需要这两种方法的值来替换 Foo 和 Bar” - 为此你需要设置器。 “我正在尝试返回单个对象数组。” - 我不明白。返回什么和在哪里?
  • @HoldOffHunger 是的,它只返回该方法的值。我想调用一次 Test 类并从每个方法中获取值。包含 $theme 和 $panel 的对象数组。
  • @El_Vanja $theme 和 $panel 在我调用 Test 类的对象数组中。
  • 看来你有很多关于类的知识。您在构造函数中应该在两种方法中执行的操作(立即将您的属性初始化为它们需要的属性)。一旦它们被初始化,编写一个将这两个值作为数组返回的方法就变得微不足道了。

标签: php class oop


【解决方案1】:

要么将代码从方法移动到__construct(),要么调用那里的方法:

public function __construct() {     
    $this->parent_theme_settings = $this->parent_theme_settings();       
    $this->admin_panel_settings  = $this->admin_panel_settings();
}   

我不知道你说的返回单个对象数组是什么意思,你不能从构造函数中return。您可以使用另一种返回数组的方法:

public function get_settings() {
    return [$this->parent_theme_settings(),
            $this->admin_panel_settings()];
}

【讨论】:

    【解决方案2】:

    我认为 foo 和 bar 是属性中的值,因此要更改这些值,您必须通过设置 setter 或为您完成工作的特殊函数来更改保存这些值的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 2016-08-28
      • 2020-07-21
      • 2015-06-08
      相关资源
      最近更新 更多