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

In this snippet:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product_variant extends Model
{

    protected $primaryKey='variant_id';

    public $translationForeignKey = $this->primaryKey;
}

This rule is not working:

public $translationForeignKey = $this->primaryKey;

How can we access this variable that is in the same scope of this class?

Either set the value in a constructor or create a getter to return the value.

// option 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;
    }

}

// option 2, you dont even need the other property in this method, unless its value may change during execution

<?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;
    }

}

At the time of defining the class you can only assign constant values to the class properties. Variables are not allowed here.

You need to do assignment part in the constructor.

<?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;
    }
}