php - 无法访问方法中的构造变量(php laravel)

标签 php laravel

我有一个基类,它像这样设置其他扩展 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/

相关文章:

php - 防止 PHP 解释源代码中字符串中的新行

php - 我如何确保来自 MySQL 的值在 PHP 中保持其类型?

php - Magento 模块 - 覆盖 Controller ,添加模板

php - 从 7.9.2 更新到 Laravel 8.x 后,$user -> links() 用户界面有问题,可能是 bootstrap

拉拉维尔 4 : avoid duplicate entry

php - 在选择首先替换字符串部分的顺序时替换字符串

PHP nodeValue 剥离 html 标签 - innerHTML 替代方案?

php - 拉维尔 5 : Eloquent & form model for business hours

php - Laravel,添加门以查看用户是否有权访问

php - Laravel 6.x - 无法更新 Controller 方法中的表单(Nested-Child)