PHP encountered the following constant error:Why?
error messages:
Symphony\Component\Debug\Exception\FatalThrowableError
syntax error, unexpected 'const' (T_CONST)
Codes Affected:
const$ABBB=300;
running environment:
%php-version
PHP 7.3.24 - (to be removed in future macOS) (cli) (build: Dec 21 2020 21:33:22) (NTS)
An error occurred among the following functions:
public function getYourAnswer($stack)
{
$calcCost=0;
const INITIAL_COST = 300;
$calcCost=calculate();
$totalCost=$calcCost+INITIAL_COST;
return$totalCost;
}
PHP does not include $
constants.
const ABBB=300;
However, the error message seems to be saying something different.
Perhaps the problem is something wrong with the previous code, not that line.
Perhaps there is no semicolon ;
at the end of the sentence.
Check it out.
PHP does not write constant declarations with const
at all variable declaration locations.
(Also, as @ItagakiFumihiko's answer says, we do not add $
to the constant name.)
For example, you can declare class constants as follows:
class MyClass {
private const INITIAL_COST = 300;
public function getYourAnswer($stack)
{
$calcCost=0;
$calcCost=calculate();
$totalCost=$calcCost+MyClass::INITIAL_COST;
return$totalCost;
}
}
Is getYourAnswer
the class method since it comes with public
?
In any case, you cannot define a constant in const within a class method or a normal function.
If you want to define it, it's outside.
class hogehoge{
const INITIAL_COST = 300;
public function getYourAnswer($stack)
{
$calcCost=0;
$calcCost=calculate();
$totalCost=$calcCost+INITIAL_COST;
return$totalCost;
}
}
If you want INITIAL_COST
to be in the function scope, consider whether it must be a constant.Isn't it okay to use a normal variable?
Also, it has nothing to do with the question, but the code provided contains a full-width space, which also causes an error.
Compared to the declaration in define()
, the const
keyword has the following limitations:
Note:
As selected to define constants using define(), constants defined using the const keyword must be degraded at the top-level scope because they are defined at compile-time. This means that they cannot be defined inside functions, loops, or duration.
© 2024 OneMinuteCode. All rights reserved.