douba8048
douba8048
2015-10-23 08:52

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

已采纳

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duanbushi1479 duanbushi1479 6年前

    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;
        }
    
    }
    
    点赞 评论 复制链接分享
  • duanmao1919 duanmao1919 6年前

    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;
        }
    }
    
    点赞 评论 复制链接分享

相关推荐