[рд╣рд▓] Classes and Objects in PHP

  

3
рд╡рд┐рд╖рдп рдкреНрд░рд╛рд░рдВрднрдХрд░реНрддрд╛

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)

рдзрдиреНрдпрд╡рд╛рдж

P.S. If you can also give examples of their usage with code... thanks

1 рдЙрддреНрддрд░
2

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┬аnew┬а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 = new DateTime();
$date2 = new DateTime();
$date3 = new DateTime();

On the picture below you can see more about the Class, Objects:

classes and objects in php

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:

classes objects php output

рд╢реЗрдпрд░ рдХрд░рдирд╛: