我有一个基类,它像这样设置其他扩展 Controller :
class BaseController extends Controller
{
public $globalCurrencies;
public $globalLanguages;
public function __construct()
{
$this->globalCurrencies = $this->getCurrencies(); // this works
$this->globalLanguages = $this->getLanguages(); // this works
}
}
我使用一个助手来扩展这个类,如下所示:
class SessionHelper extends BaseController
{
public $test;
public function __construct()
{
parent::__construct(); // fire parent aka basecontroller construct
$this->test = $this->globalCurrencies; // this works (variables are set)
echo '__construct: '.$this->test; // this even displays it
}
public function getCurrencies()
{
dd('method'.$this->test); // NOT WORKING
}
public function getCurrentCurrency()
{
return $this->getCurrencies()->where('id', Session::get('currencyId'))->first() ?? null;
}
}
稍后代码在模型中使用:
class Product extends Model
{
protected $table = "products";
public $timestamps = true;
public $sessionHelper;
public function __construct()
{
$this->sessionHelper = new SessionHelper;
}
public function getPrice($conversion_rate = null)
{
return number_format($this->price_retail / $this->sessionHelper->getCurrentCurrency()->conversion_rate, 2);
}
}
知道为什么我可以在构造变量中访问但不能在方法中访问吗?如果我没记错的话,构造首先被解雇,所以之后的一切都应该可以访问它。
最佳答案
在构造函数外声明 $test 变量为私有(private)。在构造函数中保持您现在的方式,然后为测试变量创建一个 setter 和 getter。
class testObject
{
private $test;
function __construct($test)
{
$this->test= $this->globalCurrencies;
}
// test getter
function getTest()
{
return $this->test;
}
}
关于php - 无法访问方法中的构造变量(php laravel),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55843027/