如何从同一个类访问一个类变量


How to access a class variable from same class

在代码片段中:

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Product_variant extends Model
{
    protected $primaryKey='variant_id';
    public $translationForeignKey = $this->primaryKey;
}

这个规则不起作用:

public $translationForeignKey = $this->primaryKey;

如何访问这个类的作用域内的变量?

要么在构造函数中设置该值,要么创建getter来返回该值。

//选项1

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Product_variant extends Model
{
    protected $primaryKey='variant_id';
    public $translationForeignKey = '';
    // option 1
    public function __construct()
    {
        $this->translationForeignKey = $this->primaryKey;
    }
}

//选项2,你甚至不需要这个方法中的其他属性,除非它的值在执行过程中可能改变

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Product_variant extends Model
{
    protected $primaryKey='variant_id';
    // option 2
    public function getTranslationForeignKey()
    {
         return $this->primaryKey;
    }
}

在定义类的时候,你只能给类的属性赋常量值。这里不允许使用变量。

你需要在构造函数中做赋值部分。

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Product_variant extends Model
{
    protected $primaryKey='variant_id';
    public $translationForeignKey;
    public function __construct() 
    {
        $this->translationForeignKey = $this->primaryKey;
    }
}