OOPs Tutorials
- What is OOPs
- Access Modifier
- Constructor
- Destructor
- Polymorphism
- Inheritence
- Method Overriding
- Abstract class
- Interface
- Traits
- This keyword
- static keyword
- Final keyword
- Class Constant
- Exception Handling
- Binding in php
- tostring in php
- Object Iteration
- Reflection
- Magic methods
- Namespaces
- CRUD Function
- OOPs CRUD
- CRUD Example
Important Links
What is Namespaces?
Namespaces allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class
Namespaces are declared at the beginning of a file using the namespace keyword:
File Name :
namespace Ittutorial;
Example
File Name :
<?php
namespace Ittutorial;
class Myclass{
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
$obj = new Myclass();
$obj->title = "My table";
$obj->numRows = 5;
?>
<!DOCTYPE html>
<html>
<body>
<?php
$obj->message();
?>
</body>
</html>
Declare a namespace called ittutorial inside a namespace called Code:
File Name :
namespace Code\Ittutorial;
Html.php
File Name :
<?php
namespace Html;
class Table {
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
class Row {
public $numCells = 0;
public function message() {
echo "<p>The row has {$this->numCells} cells.</p>";
}
}
?>
index.php
File Name :
<?php
include "Html.php";
$table = new Html\Table();
$table->title = "My table";
$table->numRows = 5;
$row = new Html\Row();
$row->numCells = 3;
?>
<html>
<body>
<?php $table->message(); ?>
<?php $row->message(); ?>
</body>
</html>
Namespace Alias
It can be useful to give a namespace or class an alias to make it easier to write. This is done with the use keyword:
File Name :
<?php
include "Html.php";
use Html as H;
$table = new H\Table();
$table->title = "My table";
$table->numRows = 5;
?>
<html>
<body>
<?php $table->message(); ?>
</body>
</html>