OOP(Object Oriented Programming ) help us to reduce the code, easy to maintenance and reduce the errors,...etc. OOP is used in Java,C++,....
Today I will show you how create an easy connection using OOP in PHP.
Let go a head,
1/.Create class file: "MyClass.class.php": Then write the code bellow
Today I will show you how create an easy connection using OOP in PHP.
Let go a head,
1/.Create class file: "MyClass.class.php": Then write the code bellow
class database{
private $con;
public function __construct(){
$this->con=mysqli_connect("localhost","root","","sblog");
if(!$this->con){
die("Can not connect to Database server!".mysqli_connect_errno($this->con));
}
}
public function setCon($con){
$this->con=$con;
}
public function getCon(){
return $this->con;
}
}
2/.After creating class you need to call it for connection:
->Create an "Index.php" file then write some code to create the new object from MyClass.class.php
Before you create new object you need to include class file:
require "myClass.class.php";
$data=new database;
Full Code
1/.Class: <?php class database{ private $con; public function __construct(){ $this->con=mysqli_connect("localhost","root","","sblog"); if(!$this->con){ die("Can not connect to Database server!".mysqli_connect_errno($this->con)); } } public function setCon($con){ $this->con=$con; } public function getCon(){ return $this->con; } } ?> 2/.Index
<?php
require "myClass.class.php";
$data=new database;
?>