0

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
  • 1
    Just an observations : I would have expected Product_variant to extend Product Commented Oct 23, 2015 at 8:59
  • 3
    You need to assign the properties value in the constructor, via a setter method or by setting the property after the class has been instantiated. Commented Oct 23, 2015 at 9:01

2 Answers 2

2

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

}
Sign up to request clarification or add additional context in comments.

2 Comments

Just remove the $ after $this-> :)
@AshwiniAgarwal Thanks, copy/paste will get you Every Time
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.