3
21/10/2024 1:31 pm
Konu başlatıcı
Can you please explain the classes and objects in PHP?
I know they are the core of understanding the OOP in Php (Object-oriented programming)
Teşekkürler
P.S. If you can also give examples of their usage with code... thanks
1 Yanıt
2
21/10/2024 1:32 pm
In PHP classes provide the structure for objects and act as template for objects of the same type. Functions used in Class are called methods, the variables are called properties;
Class:
- Use keyword yeni to create objects and invoke constructors
- A class can have many instances (objects)
- Use PascalCase for Class naming
- Class is made up of state and behavior
- Getters and Setters provide access to the fields
- Functions describe behaviour
- Fields store values
- Fields (private variables), e.g. day, month, year
- Data, e.g. getDay, setMonth, getYear
- Actions (behavior), e.g. plusDays(count), subtract(date)
One class may have many instances (objects)
- Sample class: DateTime
- Sample objects: peterBirthday, mariaBirthday
Objects:
- Objects are Instances of Classes
- Creating the object of a defined class is called instantiation
- The instance is the object itself, which is created runtime
All instances have common behaviour:
$date1 = yeni DateTime();$date2 = yeni DateTime();$date3 = yeni DateTime(); |
On the picture below you can see more about the Class, Objects:

Here is one example taken from this video:
<?php
class Game
{
var $price;
var $name;
var $photo;
var $dir = "games/";
public function print_game() {
echo $this->name . PHP_EOL;
echo $this->price . PHP_EOL;
echo $this->dir . $this->photo . PHP_EOL;
}
public function set_game($name, $price, $photo) {
$this->name = $name;
$this->price = $price;
$this->photo = $photo;
}
}
$game = new Game();
$game->name = "Metro";
$game->price = 49;
$game->photo = "metro.jpg";
$game->print_game();//1st game: Metro (printing)
$game->name = "Detroit Become Human";
$game->price = 59;
$game->photo = "detroit.jpg";
$game->print_game();//2nd game: Detroit Become Human (printing)
$game->set_game("Little Big Planet 3", 49, "lbp3.jpg");
$game->print_game();//3rd game: Little Big Planet 3 (printing)
and the output:

