Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 7, Fatal error: Constant expression contains invalid operations [closed]

Tags:

php

mysql

php-7

I am building a login sequence for a website that I am designing for a school project with MySQL and PHP7 (which I am relatively new to). I need some help understanding what this error means and how I can resolve the issue:

Fatal error: Constant expression contains invalid operations in C:\Abyss Web Server\htdocs\login_tools.php on line 19

Here is the line of code for a function which ensures a login has succeeded and retrieves the associated user details:

function validate($dbc, $email=",$pwd=")
like image 228
JO'Donnell Avatar asked Dec 18 '22 13:12

JO'Donnell


2 Answers

I think an explanation of this error message is valuable since it's new to PHP 7 - Let's reframe this for clarity:

<?php

function validate($dbc, $email="$foo"){
}

?>

As a beginner, you probably would have found PHP 5.6's error message more helpful for debugging:

PHP Parse error: syntax error, unexpected '"' in /home/hpierce/test.php on line 3

However PHP 7 displays the error you've found:

Fatal error: Constant expression contains invalid operations in /home/hpierce/test.php on line 3

When you declare an optional argument, as you have with $email, you are required to provide a literal value (a "constant expression") that stands alone without needing to be evaluated (determined by using "invalid operations"). By including a reference to $foo, you've declared your optional argument by using a dynamic expression which isn't valid here.

Examples of providing constant expressions:

//Providing an integer literal
function validate($dbc, $email=1){}

//Providing a string literal
function validate2($dbc, $email="foo"){}

//Providing an array literal
function validate3($dbc, $email=Array("foo", "bar")){}

This rule applies to any situation where you need to define constant expressions, such as adding a class constant:

<?php

class Foo
{
    //Fatal error: Constant expression contains invalid operations
    const BAR = $bar;
}

?>
like image 90
HPierce Avatar answered Dec 30 '22 17:12

HPierce


As you can see by the line of code you posted you used a single double quote in the function declaration. If you look closely you'll see that ,pwd=" is all in red because of the single double quote after $email=

Either change the double quote to 2 single quotes or add another double quote.

function validate($dbc, $email='',$pwd='')

OR

function validate($dbc, $email="",$pwd="")
like image 37
Dave Avatar answered Dec 30 '22 19:12

Dave