PHP Fundamentals:
1.PHP SYNTAX:
Like HTML, you need to have the opening tag to start PHP code:
<?php
If you mix PHP code with HTML, you need to have the
enclosing tag:
?>
2.PHP VARIABLES:
- Variables are used to store data.
- Variables names start with a dollar sign($).
- The first character after the dollar sign ($) must be a letter (a-z) or the underscore (_).
- The remaining characters can be underscores, letters, or numbers.
- PHP is loosely typed, meaning you don’t need to declare the data type of a variable.
3.CONSTANTS:
A PHP constant is like a container that holds a value that doesn’t change. It’s like a label that you stick on something and it stays the same no matter what. It’s really handy when you have a value that you want to use over and over again without having to type it out every time. So, you can think of a PHP constant as a way to store a value that won’t change.
For example:
Let’s say you have a website and you want to set a constant for the maximum number of characters allowed in a username. You can define a PHP constant like this:
php
define(‘MAX_USERNAME_LENGTH’,20);
Now, whenever you need to check the maximum length of a username, you can simply use the constant
`MAX_USERNAME_LENGTH` instead of typing out the number 20 every time. It makes your code cleaner and easier to maintain.
Note: The ‘define()’ function in PHP is used to create a constant. It takes two arguments: the name of the constant and its value. For example:
php
define(‘MY_CONSTANT’,”HELLO,WORLD!’);
In this case, we created a constant called ‘MY_CONSTANT’ with the value ‘HELLO,WORLD!’. Once defined, the constant’s value cannot be changed throughout the script. It’s a handy way to store values that won’t change.
Difference Between Define() and Constant()
So, the difference between `define()` and `constant()` in PHP is how they are used to create constants.
The `define()` function is used to define a constant by providing a name and a value, like this:
```php
define('MY_CONSTANT', 'Hello, World!');
```
On the other hand, the `constant()` function is used to retrieve the value of a constant by providing its name, like this:
```php
$value = constant('MY_CONSTANT');
```
So, while `define()` is used to create a constant, `constant()` is used to access the value of an existing constant.
4.COMMENTS:
In PHP, you can add comments to your code to make it more understandable for yourself and others who might read it. There are two types of comments in PHP:
- Single–line comments:
These comments start with `//` and only apply to the current line. For example:
```php
// This is a single-line comment
```
2.Multi–line comments:
These comments start with `/*` and end with `*/`. They can span multiple lines. For example:
“`php
/*
This is a multi-line comment.
It can have multiple lines of text.
*/
“`
Comments are not executed as part of the code, so they don’t affect the functionality of your program.