我想知道如何传递一个在类中的函数之间设置的对象?编辑:因此,如果尚未设置,该函数仅使用默认值。
因此,例如下面我在构造函数中有对象objAuthParams中的默认参数。如果我想调用该类并更改这些参数,我知道我可以通过创建一个新类来实现这一点但在该实例中如何将新值传递给函数 oauthorise ?
我花了很多时间在网上搜索,但你可能会说我无法清楚表达我想要做的很好而且我非常生疏,PHP会非常感谢任何指针/解释我错了!
这是代码
class oauth {
public $objAuthParams;
// Construnct
public function __construct() {
$this->objAuthParams = (object) array(
"method" => "GET",
"access_token" => "a token",
"access_token_secret" => "a secret",
"consumer_key" => "b consumer",
"consumer_secret" => "b secret"
);
$this->oauthorise();
}
public function oauthorise() {
echo $this->objAuthParams->method;
}
} // eoc
// Attempt to set new params for method
$class = new oauth;
$class->objAuthParams->method = "im a hairy badger";
答案 0 :(得分:1)
您可以将objAuthParams
对象传入构造函数。如果已设置,则将$onjAuthParam
变量设置为注入的变量。
<?php
class oauth {
public $objAuthParams;
// Construnct
public function __construct($objAuthParams = false) {
if(!$objAuthParams)
$this->objAuthParams = (object) array(
"method" => "GET",
"access_token" => "a token",
"access_token_secret" => "a secret",
"consumer_key" => "b consumer",
"consumer_secret" => "b secret"
);
else
$this->objAuthParams = $objAuthParams;
$this->oauthorise();
}
public function oauthorise() {
echo $this->objAuthParams->method;
}
}
$myAuthParams = (object)array(
"method" => "im a hairy badger",
"access_token" => "a token",
"access_token_secret" => "a secret",
"consumer_key" => "b consumer",
"consumer_secret" => "b secret"
);
$class = new oauth($myAuthParams);
print_r($class);
$class2 = new oauth();
print_r($class2)
这是指依赖注射。 - http://net.tutsplus.com/tutorials/php/dependency-injection-in-php/