search

Home  >  Q&A  >  body text

Invalid operation causes constant expression to be invalid

<p>I have the following code and when I define a variable in the constructor I get the error "PHP Fatal Error: Constant expression contains an invalid operation". It works fine when used in Laravel framework. </p> <pre class="brush:php;toolbar:false;"><?php namespace App; class Amazon { protected $serviceURL = config('api.amazon.service_url'); public function __construct() { } }</pre> <p>I saw this question: PHP error: fatal error: constant expression contains an invalid operation But my code doesn't declare any static content, so this answer doesn't solve my problem. </p>
P粉418854048P粉418854048458 days ago497

reply all(2)I'll reply

  • P粉391955763

    P粉3919557632023-08-23 17:39:51

    This method does not allow initialization of class attributes. You have to move the initialization into the constructor.

    reply
    0
  • P粉652523980

    P粉6525239802023-08-23 17:05:59

    As described here

    The only way you can make it work is:

    <?php
    
    namespace App;
    
    class Amazon
    {
      protected $serviceURL;
    
      public function __construct()
      {
        $this->serviceURL = config('api.amazon.service_url');
      }
    }

    reply
    0
  • Cancelreply