OOP PHP Class, Object, this keyword, Method, Properties

Author: Al-mamun Sarkar Date: 2020-04-18 10:31:50

এই lesson এ Object Oriented PHP, PHP Class তৈরি করা, Class এর Object তৈরি করা, this keyword এর ব্যবহার, Method and Properties এর ব্যবহার জানব। 

 

class.php

class Student {
	public $id = 10;
	public $name = 'Akash';
}


$student = new Student();
echo $student->name;
$student->name = 'Sagor';
echo "<br>";
echo $student->name;

 

class_with_functions.php

class Math {
	public $a = 10;
	public $b = 20;

	public function sum() {
		$c = $this->a + $this->b;
		return $c;
	}

	public function sum_result() {
		$this->a = 15;

		echo 'Sum is ' . $this->sum();
	}
} 

$math = new Math();

echo $math->sum();
echo '<br>';
$math->b = 30;
$math->sum_result();
echo '<br>';
echo $math->a;

 

Constructor.php

class Math {

	public $a;
	public $b;
	
	public function __construct($first, $second = 15) {
		$this->a = $first;
		$this->b = $second;
		$this->display();
	}

	public function sum() {
		return $this->a + $this->b;
	}
	public function mul( $c = 2 ) {
		return $this->a * $this->b * $c;
	}
	public function display() {
		echo "Welcome boss <br/>";
	}
}

$foo = new Math(10, 20);
echo $foo->sum();
echo "<br>";
$obj = new Math(30);
echo $obj->sum();
echo "<br>";
echo $obj->mul(3);

 

many_class.php

class A {
	public function welcome() {
		echo "Welcome to A";
	}
}

class B {
	public function wel() {
		echo "Welcome to B";
	}
}

 

multiple_object.php

class Student {
	public $id = 10;
	public $roll = 20;
}

$sakib = new Student();
$rakib = new Student();

$sakib->id = 12;
echo $sakib->id;
echo "<br>";
echo $rakib->id;

 

test.php

require "many_class.php";

$obj = new A();
// $b = new B();

if ( $obj instanceof A ) {
	$obj->welcome();
}