【问题标题】:How to pass value to a public function within a class in PHP?如何将值传递给 PHP 类中的公共函数?
【发布时间】:2017-11-24 13:24:54
【问题描述】:

这是我一直在编写的代码,我想从外部将值传递给类中的函数!怎么做?

class components {
  private $senderID;
  function __construct($sender) {
      $senderID = $sender;
  }
function hello($name) {
$jsonData = '{
"recipient":{
    "id":"'.$this->senderID.'",
    "name":"'.$name.'"
  }
}';
}
}

$component = new components($sender);
$component->hello('Rohit');

这似乎不起作用!请帮忙!!

【问题讨论】:

  • “不起作用”如何?你定义过$username吗?你期望这个函数的结果是什么?这是怎么失败的?
  • 该死,当你看到过去的自己提出如此愚蠢的问题时的感觉 :) 无论如何,谢谢你们的帮助!!

标签: php function class object


【解决方案1】:

您没有在构造中使用$this 在对象范围内设置senderID 的值。这样做:

function __construct($sender) {
    $this->senderID = $sender;
}

只需将您的 __construct 方法更改为这样,它就会起作用。

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 2020-09-17
    相关资源
    最近更新 更多