PHP Notes
PHP Notes
CH.1
Q1. Data Types
1. **Integer**:
```php
$age = 30;
$count = -5;
```php
$price = 19.99;
$pi = 3.14159;
```
3. **String**:
```php
```
4. **Boolean**:
```php
$is_active = true;
$has_permission = false;
```
5. **Array**:
```php
$person = array("name" => "John", "age" => 30, "city" => "New York");
```
6. **Object**:
```php
class Car {
public $brand;
public $model;
$this->brand = $brand;
$this->model = $model;
```
7. **NULL**:
```php
$no_value = null;
```
8. **Resource**:
```php
```
Switch Statement
```php
switch (expression) {
case value1:
break;
case value2:
break;
default:
```
- If a match is found, the code block following that case is executed until
a "break" statement is encountered.
- If no match is found, the code block following the "default" case (if
provided) is executed.
```php
$day = "Monday";
switch ($day) {
case "Monday":
break;
case "Tuesday":
break;
case "Wednesday":
break;
default:
```
Foreach loop
The foreach construct provides the easiest way to iterate the array elements. It
works on array and objects both. The foreach loop though iterates over an array of
elements, the execution is simplified and finishes the loop in less time
comparatively. It allocates temporary memory for index iterations which makes the
overall system to redundant its performance in terms of memory allocation.
Syntax:
foreach( $array as $element ) {
// PHP Code to be executed
}
CH.2
Q1. Explain implode() and explode()
In PHP, `implode()` and `explode()` are two functions commonly used for
handling strings:
```php
<?php
?>
```
```php
<?php
$string = "apple,banana,orange";
print_r($array); // Output: Array ( [0] => apple [1] => banana [2] =>
orange )
?>
```
Here, `explode(',', $string)` splits the `$string` at each comma `,` and
stores the substrings into the `$array`.
1. Constructor*
```php
<?php
class MyClass {
?>
Destructors
If you create a __destruct() function, PHP will automatically call this function
at the end of the script.
Notice that the destruct function starts with two underscores (__)!
The example below has a __construct() function that is automatically called
when you create an object from a class, and a __destruct() function that is
automatically called at the end of the script:
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
Inheritance
Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and
methods from the parent class. In addition, it can have its own
properties and methods.
An inherited class is defined by using the extends keyword.