有没有办法在两个函数中使用从类中实例化的对象变量?
这是我尝试过的代码,但它只是返回null
:
class bookAppointmentsController extends APIController
{
private $business;
public funcition check($key)
{
$this->business = new APIClass();
$setconnection = $this->business->connectAPI($key);
}
public function book()
{
dd($this->business) //returns null
$this->business->book();
}
}
我试图在两个函数中使用$business
对象,但它不起作用,当我dd($business)
它返回null
有什么办法吗?
答案 0 :(得分:0)
也许解决方案可能是变量全局
您可以将变量设为全局:
function method( $args ) {
global $newVar;
$newVar = "Something";
}
function second_method() {
global $newVar;
echo $newVar;
}
或者您可以从第一种方法返回它并在第二种方法中使用它
public function check($key)
{
$this->business = new APIClass();
$setconnection = $this->business->connectAPI($key);
return $this->business;
}
public function book()
{
$business = check($key);
$business->book();
}
答案 1 :(得分:0)
将实例化移动到构造函数:
public function __construct(APIClass $business)
{
$this->business = $business;
}
然而,如果你让Laravel做重担并为你准备APIClass
会更好。
在注册方法下的AppServicePorvider
下,您可以创建APIClass
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind('APIClass', function ($app) {
$api = new APIClass();
// Do any logic required to prepare and check the api
$key = config('API_KEY');
$api->connectAPI($key);
return $api;
});
}
查看documentations了解详情。