Constant in PHP
- Constants are PHP container that remain constant and never change
- Constants are used for data that is unchanged at multiple place within our program.
- Variables are temporary storage while Constants are permanent.
- Use Constants for values that remain fixed and referenced multiple times.
Rules for defining constant
- Constants are defined using PHP’s define( ) function, which accepts two arguments:
The name of the constant, and its value. - Constant name must follow the same rules as variable names, with one exception the “$” prefix is not required for constant names. Syntax:
Valid and Invalid Constant declaration:
Create a constant and assign your name
Output
Hello Rexx
In the above exampleHello Rexx
We define a constant using define( ) function. first argument for name of constant and second for its value=”phptpoint”.
Now we print the value. Pass name of constant inside print statement
Output will become
Sum of two numbers using constant
Output
Sum of two constant = 200
In the above exampleSum of two constant = 200
We declare three constant of name=(ONE,TWO,SUM). First Add the value of two constant.
Now sum of these two value work as a value for third define constant(SUM).
Now pass $sum inside print it will show the sum of two number.
Subtraction of two numbers using constant
Ex.iii
Output
Subtraction of given number = 500
In the above exampleSubtraction of given number = 500
We define three constant with name(X,Y,Z). First subtract the value of two defined constant .
Now result of these two value work as a value for third define constant(Z).
Pass Z inside print so it will show the subtraction of two value.
Sum of two numbers and assign the result in a variable
Output
Sum of two constant = 200
In the above exampleSum of two constant = 200
We define two constant with name(one,two) and value(100,100) respectively.
$res variable is also define.
Now we perform addition of two defined constant value and result store in a variable($res = one+two;).
To print the result pass $res inside print statement.
Building a Dollars-to-Euros Converter
Output
if you have been following along, the script should be fairly easy to understand.USD/EUR Currency Conversion
150 USD is equivalent to :120 EURIt begins by defining a constant named “EXCHANGE_RATE” which surprise, surprise stores the dollar-to-euro exchange rate(assumed here at 1.00 USD to 0.80 EUR).
Next, it defines a variable named “$dollars” to hold the number of dollars to be converted, and then it performs an arithmetic operation using the * operator, the “$dollars” variable, and the “EXCHANGE_RATE” constant to return the equivalent number of euros.
This result is then stored in a new variable named “$euros” and printed to the Web page.
No comments:
Post a Comment