Constant expression contains invalid operation php

Prepare for PHP 7 error messages (part 2)

In the article “Prepare for PHP 7 error messages (part 1)” from last week, we covered the evolution of error messages in the PHP binary. In order to prepare for prepare for PHP 7 error messages, we are now going to review the new messages that are appearing in PHP 7. We’ll also see some of those that are disappearing : it’s good to know we won’t meet them again.

Читайте также:  Html css hover transition

« Return value of %s%s%s() must %s%s, %s%s returned »

The first extra error messages is linked to the new feature called Return Type Hint. This works like Type Hint, but is applied to returned values. At definition time, it is possible to specify which type of value will be returned. This is achieved by adding a colon and a type hint after the function signature :

function myFunction (\MyClass $anObject): \MyOtherClasss < return new \MyOtherClass($anObject->toOtherConfig()); >

The error message will be thrown anytime the return value doesn’t match the specified return type hint. Both Type Hinting (in- and outgoing) aims at enforcing that correct values are passed in and out in a method. Libraries will probably be keen on adopting them, leading to a transition phase where lots of this error message have to be cleaned.

« Cannot declare a return type of %s outside of a class scope »

Linked to the previous, it is possible to use the special keywords ‘self’ and ‘parent’ when defining a Type Hint (‘static’ is not supported). This error message will be emitted if a function makes use of them : only methods, inside a class, can use them. The error will be raised at execution time : linting can’t spot that.

Class MyClass extend MyParentClass < public function myFunction (self $anObject): parent < return new parent($anObject->toOtherConfig()); > >

« Constructor %s::%s() cannot declare a return type »
« Destructor %s::%s() cannot declare a return type »
« %s::%s() cannot declare a return type »

There are some methods that doesn’t require a Return Type hint : Constructor, Desctructor and __clone. All of them are called at object initialization, and no returning value is actually expected : the most important is the process to build (or unbuild) the new object. As such, Return Type Hint are useless in those methods.

Читайте также:  Javascript click event this

PHP 4 constructors are also supported, and it will be fun to find code that mix emerging Return Type hint feature with legacy PHP 4 constructor. Mail me when you find one.

Note that return inside such method are also unused, but do not generate any error message : one can use a return in a __construct, to interrupt the method early. The returned value, often a null, will just be ignored.

« Constant expression contains invalid operations »

This message will help everyone who is using the recent Constant Scalar expression. This new features allows a certain number of operations to be performed when creating a new constant. For example,

const SQUARE_OF_TWO = 2 * 2;

So, most operators are allowed, including ternary operator, logical, comparison, array pair and math operations but not assignations.Variables are all forbidden but normal, magic and class constants are valid. Functioncall are forbidden except array(). More about this : https://wiki.php.net/rfc/scalar_type_hints_v5

This message is one of the direct advantages of the new AST in PHP : where PHP 5.6 is emitting an fatal error because it has reached an error, the AST allows PHP to check the situations and validate it graciously.

« Constants cannot be recursive arrays »
« Constants may only evaluate to scalar values or arrays »

Those errors are also better messages linked to the creation of constants based on structure that can’t be constants, such as objects, resources or recursive arrays. This last one is an array which contains a reference to itself. PHP 7 accepts arrays with references, though they will be dropped by the constant, and only values will be kept.

« Cannot use temporary expression in write context »

The AST is also at the origin of this new message : with the universal variable syntax, some situations are now possible, like nesting :: ($foo::$bar::$baz) or using immediately some object without storing it (new someClass)().

Some newly supported situations will then generate errors, like ‘foo'[0] = ‘b’. This instruction changes the first character for the string ‘foo’, but since the string is not stored in a variable, the result is lost anyway. The result is not necessarily lost, since such expression could be nested in a parenthesis and assigned like $x = (‘foo'[0] = ‘b’) ;. PHP 5.6 doesn’t accept anything like that (fails with a fatal error), so it old code may not generate such errors.

function a(&$b) < /**/ >a([0, 1][0]); // Trying to pass by reference a non-variable

The list of situations that will lead to this error are not explicit (yet), though there are 34 occurrences of this message in the PHP source. Playing with too many literals will probably lead to it. Read more about this in https://wiki.php.net/rfc/uniform_variable_syntax.

To be continued

That will be all for this week. We’ll have another set of PHP 7 error messages next week.

Источник

PHP Error : Fatal error: Constant expression contains invalid operations

Fatal error: Constant expression contains invalid operations in config.php on line 214

 protected static $dbname = 'mydb_'.$appdata['id']; 

Whether I did any mistakes in quotes? Or somewhere else?

My search for the error message only showed a different source cause (a dynamic default value in a function definition).

Answer

Solution:

Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.

So you cannot initialize a static variable with another variable. Replace $appdata[‘id’] with a constant string or remove the static attribute.

This is because all static declarations are resolved in compile-time, when the content of other variables is not known (see this other page of official doc).

Answer

Solution:

Unless you mess with reflection, the only way I can think of to have a static private/protected class property with a dynamically generated value is to calculate it outside the class:

class Foo < protected static $dbname = DBNAME; public static function debug() < return Foo::$dbname; >> $appdata = array( 'id' => 31416, ); define('DBNAME', 'mydb_'.$appdata['id']); var_dump(Foo::debug()); 

In your precise use case, however, it’s possible that there’s simply no good reason for the property to be static. In that case, it’s as straightforward as using the constructor:

class Foo < protected $dbname; public function __construct($appdata)< $this->dbname = 'mydb_'.$appdata['id']; > public function debug() < return $this->dbname; > > $appdata = array( 'id' => 31416, ); $foo = new Foo($appdata); var_dump($foo->debug()); 

Answer

Solution:

This is because a static variable contains a constant value in it. But in your case:

protected static $dbname = 'mydb_'.$appdata['id']; 

$appdata[‘id’] is dynamic that can change its value during the execution. That’s why the error is showing.

Answer

Solution:

I had this error and my fix was to not declare a date within a class property array

public static $config_array = array( 'start_date' => date('Y-m-d H:i:s') // No can do ); 

Answer

Solution:

For your information:- I got the same error by using some characters in a constant expressions.

This is what caused the error and I removed this || which is the logical OR operator characters from the string and it worked.

Share solution ↓

Additional Information:

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

Fatal error Constant expression contains invalid operations

  • All categories
  • ChatGPT (11)
  • Apache Kafka (84)
  • Apache Spark (596)
  • Azure (145)
  • Big Data Hadoop (1,907)
  • Blockchain (1,673)
  • C# (141)
  • C++ (271)
  • Career Counselling (1,060)
  • Cloud Computing (3,469)
  • Cyber Security & Ethical Hacking (162)
  • Data Analytics (1,266)
  • Database (855)
  • Data Science (76)
  • DevOps & Agile (3,608)
  • Digital Marketing (111)
  • Events & Trending Topics (28)
  • IoT (Internet of Things) (387)
  • Java (1,247)
  • Kotlin (8)
  • Linux Administration (389)
  • Machine Learning (337)
  • MicroStrategy (6)
  • PMP (423)
  • Power BI (516)
  • Python (3,193)
  • RPA (650)
  • SalesForce (92)
  • Selenium (1,569)
  • Software Testing (56)
  • Tableau (608)
  • Talend (73)
  • TypeSript (124)
  • Web Development (3,002)
  • Ask us Anything! (66)
  • Others (2,231)
  • Mobile Development (395)
  • UI UX Design (24)

Join the world’s most active Tech Community!

Welcome back to the World’s most active Tech Community!

Subscribe to our Newsletter, and get personalized recommendations.

GoogleSign up with Google facebookSignup with Facebook

Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

  • DevOps Certification Training
  • AWS Architect Certification Training
  • Big Data Hadoop Certification Training
  • Tableau Training & Certification
  • Python Certification Training for Data Science
  • Selenium Certification Training
  • PMP® Certification Exam Training
  • Robotic Process Automation Training using UiPath
  • Apache Spark and Scala Certification Training
  • Microsoft Power BI Training
  • Online Java Course and Training
  • Python Certification Course
  • Data Scientist Masters Program
  • DevOps Engineer Masters Program
  • Cloud Architect Masters Program
  • Big Data Architect Masters Program
  • Machine Learning Engineer Masters Program
  • Full Stack Web Developer Masters Program
  • Business Intelligence Masters Program
  • Data Analyst Masters Program
  • Test Automation Engineer Masters Program
  • Post-Graduate Program in Artificial Intelligence & Machine Learning
  • Post-Graduate Program in Big Data Engineering

COMPANY

WORK WITH US

DOWNLOAD APP

appleplaystore googleplaystore

CATEGORIES

CATEGORIES

  • Cloud Computing
  • DevOps
  • Big Data
  • Data Science
  • BI and Visualization
  • Programming & Frameworks
  • Software Testing © 2023 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved. Terms & ConditionsLegal & Privacy

Источник

Оцените статью