【问题标题】:PHP - Pass Argument to class __construct on call?PHP - 在调用时将参数传递给类 __construct?
【发布时间】:2015-04-29 13:46:49
【问题描述】:
class Portfolio extends Rest{   
    public $pdo;
    public $lanx;

    public function __construct($uid, $langx){
        $this->lanx = $langx;
        $db = Database::getInstance();
        $this->pdo = $db->getConnection();
    }

当我从Portfolio调用函数时

Portfolio::newItem();

如何将$uid$langx 传递给班级?

【问题讨论】:

  • 你的构造函数没有使用$uid参数,这是为什么呢?
  • Portfolio::newItem(); 正在静态调用该方法 - 您没有创建 Portfolio 的新实例,因此不会调用构造函数。首先创建一个新的 Portfolio 对象(使用实例化参数),例如 $p = new Portfolio($uid, $langx),然后调用该对象的 newItem 方法 $p->newItem() ... 除非有我们看不到的 Singleton 或 Factory 模式。
  • 我已经删除了 Jack 的一些代码。我创建了一个新实例。

标签: php class call


【解决方案1】:

使用如下参数调用静态方法是一个更好的选择:

Portfolio::newItem($uid, $langx);

在方法定义中:

public static function newItem($uid = null, $langx = null) {
    //Check Vars are set or not if not set them 
    //If all vars passed null and not sett in class throw exception
}

【讨论】:

    【解决方案2】:
    $object = new MyClass($param1, $param2);
    

    就像调用函数一样。还要注意该构造的“必需”和“可选”参数。

    【讨论】:

      【解决方案3】:
      Portfolio $p = new newItem($uid, $langx);
      

      【讨论】:

      • 你在考虑另一种语言吗?
      • 不远$p = new Portfolio($uid, $langx)
      • 虽然这可能会回答问题,但在您的答案中加入一些文字来解释您在做什么总是一个好主意。阅读how to write a good answer
      • 对不起,我在想java!
      猜你喜欢
      • 2010-12-08
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 2020-01-28
      • 2021-12-10
      • 2020-01-13
      • 2019-05-16
      • 1970-01-01
      相关资源
      最近更新 更多