-
Notifications
You must be signed in to change notification settings - Fork 0
/
34 OOP Classes and Objects.php
79 lines (70 loc) · 1.65 KB
/
34 OOP Classes and Objects.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!-- PHP OOP - Classes and Objects -->
<title>PHP OOP - Classes and Objects</title>
<!-- OOP stands for Object-Oriented Programming -->
<?php
// Note: In a class, variables are called properties and functions are called methods!
#Define A Class
class Fruit
{
#Properties
public $name;
public $color;
#Method
function set_name($fruitName)
{
$this->name = $fruitName;
}
function set_color($fruitColor)
{
$this->color = $fruitColor;
}
function get_name()
{
return $this->name;
}
function get_color()
{
return $this->color;
}
}
#Define An Objects
$apple = new Fruit();
$banana = new Fruit();
// Set Object Properties
$apple->set_name('Apple');
$apple->set_color('Red');
$banana->set_name('Banana');
$banana->set_color('Yellow');
// Get Object Properties
echo $apple->get_name() . " : " . $apple->get_color();
echo "<br>";
echo $banana->get_name() . " : " . $banana->get_color();
echo "<br>";
#You can use the instanceof keyword to check if an object belongs to a specific class
var_dump($apple instanceof Fruit);
?>
<hr>
<!-- Outside the Class (Directly Changing and Accessing the Property Value) -->
<?php
// Define A Class
class Mobile
{
// Properties
public $name;
public $model;
public $color;
}
// Define An Object
$samsung = new Mobile();
// Outside the Class (Directly Changing the Property Value)
$samsung->name = "Samsung Galaxy";
$samsung->model = "Galaxy A52s 5G";
$samsung->color = "Black";
// Outside the Class (Directly Accessing the Property Value)
echo $samsung->name;
echo "<br>";
echo $samsung->model;
echo "<br>";
echo $samsung->color;
echo "<br>";
?>