Change Value of Parent Property in PHP

Viewed 734

I've got a parent class with some default properties. In the child class, I want to update those properties directly, without using a method. Why? I believe it's a clean way of defining functionality in the child class.

So here's my parent class:

<?php 

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class BaseFormRequest extends FormRequest 
{
    protected static $NEEDS_AUTHORIZATION = false;
    protected static $FORM_RULES          = [];

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize() : bool
    {
        //dd($this->authorize);
        return self::$NEEDS_AUTHORIZATION;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() : array
    {
        return self::$FORM_RULES;
    }
}

In my child class, I'd like to do something similar to the following:

<?php

namespace App\Http\Requests;

use App\Http\Requests\BaseFormRequest;

class RegisterUserRequest extends BaseFormRequest
{

    protected static $NEEDS_AUTHORIZATION = true;
    protected static $FORM_RULES = [ /* specific form rules for this form */];
}

I don't know whether this would be the right way to do it. My question is whether I can do something similar? If I have 5 form request classes extending BaseFormRequest I'd just need to override NEEDS_AUTHORIZATION and FORM_RULES, which looks much cleaner than creating the same methods (authorize() and rules()) over and over in every class.

2 Answers

You can do it. If it's not working for you right now, it's because you are not taking advantage of late static binding.

Basically, in your methods rules() and authorize() you are making reference to self, whereas you should be making reference to static for this to work as you would expect.

E.g.:

public function rules() : array {
   return static::$FORM_RULES;
}

You can see an example of this working here

You can use Constructors for your purpose.

<?php

namespace App\Http\Requests;

use App\Http\Requests\BaseFormRequest;

class RegisterUserRequest extends BaseFormRequest
{

    public function __construct()
    {
        parent::__construct();
        BaseFormRequest::NEEDS_AUTHORIZATION = true;
        BaseFormRequest::FORM_RULES = [ /* specific form rules for this form */];
    }
}
Related