【问题标题】:How to access a class variable from same class如何从同一类访问类变量
【发布时间】:2016-01-22 18:07:34
【问题描述】:

在这个sn-p中:

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

我们如何访问这个在这个类的同一范围内的变量?

【问题讨论】:

  • 只是一个观察:我希望Product_variant 扩展Product
  • 您需要在构造函数中分配属性值,通过 setter 方法或通过设置属性类实例化之后。

标签: php class oop variables


【解决方案1】:

要么在构造函数中设置值,要么创建一个 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;
    }

}

【讨论】:

  • 只需删除$ 之后的$this-&gt; :)
  • @AshwiniAgarwal 谢谢,复制/粘贴会让你每次
【解决方案2】:

在定义类时,您只能为类属性分配常量值。这里不允许使用变量。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 2020-06-28
    相关资源
    最近更新 更多