lewis4u
lewis4u

Reputation: 15037

Laravel - Make global variable in Model to use only inside the Model

I have two variables in my Model that i use in a few functions

$firstDayThisYear = Carbon::create(date('Y'), 1, 1, 0);
$lastDayThisYear = Carbon::create(date('Y'), 12, 31, 0);

how can i extract them and make them global to use them only inside of my Model?

i know it must be protected...but I am not sure if i need to put it like this:

protected static $firstDayThisYear = Carbon::create(date('Y'), 1, 1, 0);
protected static $lastDayThisYear = Carbon::create(date('Y'), 12, 31, 0);

Upvotes: 2

Views: 6833

Answers (3)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

If you're going to use these variables in one model, just do this:

protected $firstDayThisYear;

public function __construct(array $attributes = [])
{
    parent::__construct($attributes);

    $this->firstDayThisYear = Carbon::create(date('Y'), 1, 1, 0);
}

Then use it with $this->firstDayThisYear.

Also, you could get start of the year and start of the last day of the year with:

Carbon::now()->startOfYear();
Carbon::now()->endOfYear()->startOfDay();

I guess it's more readable.

Upvotes: 4

Perovano
Perovano

Reputation: 21

If you just want this fields to be available just inside the Model, so declare it as private instead.

Upvotes: 1

Jonathon
Jonathon

Reputation: 16283

The way you've attempted to do it won't work because PHP doesn't let you use an "expression" as a default value for a property like that.

If you insist on having them static then you should create a static method to achieve this. You could do something like:

class YourModel extends Model
{
    protected static $firstDayOfThisYear;

    protected static function firstDayOfThisYear()
    {
        if (!static::$firstDayOfThisYear) {
            static::$firstDayOfThisYear = Carbon::create(date('Y'), 1, 1, 0);
        }

        return static::$firstDayOfThisYear;
    }

    public function useIt()
    {
        $firstDay = static::firstDayOfThisYear();
    }
}

Upvotes: 1

Related Questions