Constant expression contains invalid operations - Laravel
I had the following code in one of my laravel projects and it just triggered a "Constant expression contains invalid operations" error when I landed on the specific page.
I didn't actually realise the error initially, as it looks like everything ok at first. But a close look revealed minor error on lines 7 & 8. This is from the PHP manual, Have a read:
<?php namespace AppHttpControllersAuth; use AppHttpControllersController; .... .... .... class LoginController extends Controller { use AuthenticatesUsers; protected $maxAttempts = config('auth.login_attempts.web.max_attempts'); protected $decayMinutes = config('auth.login_attempts.web.decay_attempts'); public function index(){ .... .... .... } }
The error: Constant expression contains invalid operations
I didn't actually realise the error initially, as it looks like everything ok at first. But a close look revealed minor error on lines 7 & 8. This is from the PHP manual, Have a read:
If you see the last few words in the above quote, you can see that "This declaration may include an initialization, but this initialization must be a constant value", indicating that we can assign a string or number or any constant values directly during declaration. But in case, if we want to assign a dynamic value we must do it through the constructor. Following correction fixed this issue.Class member variables are called properties. They may be referred to using other terms such as fields, but for the purposes of this reference properties will be used. They are defined by using at least one modifier (such as Visibility, Static Keyword, or, as of PHP 8.1.0, readonly), optionally (except for readonly properties), as of PHP 7.4, followed by a type declaration, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value.
<?php namespace AppHttpControllersAuth; use AppHttpControllersController; .... .... .... class LoginController extends Controller { use AuthenticatesUsers; protected $maxAttempts protected $decayMinutes = config('auth.login_attempts.web.decay_attempts'); public function __constructor(){ parent::__construct(); $this->maxAttempts = config('auth.login_attempts.web.max_attempts'); $this->decayMinutes = config('auth.login_attempts.web.decay_attempts'); } public function index(){ .... .... .... } }
Look at the highlighted code inside the constructor in the above example.
- The first line calls the parent class constructor, as we are extending "Controller" we must manually call the parent class constructor. Earlier code didn't have the constructor so the parent class constructor was called automatically, But as we now have a constructor for our own class we should call the parent constructor manually.
- Values for class properties $maxAttempts and $decayMinutes are assigned with dynamic values through the constructor, so the error is gone now.
Comments (0)