Create classes and objects in php

PHP OOP — Classes and Objects

A class is a template for objects, and an object is an instance of class.

OOP Case

Let’s assume we have a class named Fruit. A Fruit can have properties like name, color, weight, etc. We can define variables like $name, $color, and $weight to hold the values of these properties.

When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

Define a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces (<>). All its properties and methods go inside the braces:

Syntax

Below we declare a class named Fruit consisting of two properties ($name and $color) and two methods set_name() and get_name() for setting and getting the $name property:

class Fruit // Properties
public $name;
public $color;

// Methods
function set_name($name) $this->name = $name;
>
function get_name() return $this->name;
>
>
?>

Note: In a class, variables are called properties and functions are called methods!

Define Objects

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.

Objects of a class are created using the new keyword.

In the example below, $apple and $banana are instances of the class Fruit:

Example

class Fruit // Properties
public $name;
public $color;

// Methods
function set_name($name) $this->name = $name;
>
function get_name() return $this->name;
>
>

$apple = new Fruit();
$banana = new Fruit();
$apple->set_name(‘Apple’);
$banana->set_name(‘Banana’);

echo $apple->get_name();
echo «
«;
echo $banana->get_name();
?>

In the example below, we add two more methods to class Fruit, for setting and getting the $color property:

Example

class Fruit // Properties
public $name;
public $color;

// Methods
function set_name($name) $this->name = $name;
>
function get_name() return $this->name;
>
function set_color($color) $this->color = $color;
>
function get_color() return $this->color;
>
>

$apple = new Fruit();
$apple->set_name(‘Apple’);
$apple->set_color(‘Red’);
echo «Name: » . $apple->get_name();
echo «
«;
echo «Color: » . $apple->get_color();
?>

PHP — The $this Keyword

The $this keyword refers to the current object, and is only available inside methods.

Look at the following example:

Читайте также:  Invocation of this java application

Example

So, where can we change the value of the $name property? There are two ways:

1. Inside the class (by adding a set_name() method and use $this):

Example

class Fruit public $name;
function set_name($name) $this->name = $name;
>
>
$apple = new Fruit();
$apple->set_name(«Apple»);

2. Outside the class (by directly changing the property value):

Example

class Fruit public $name;
>
$apple = new Fruit();
$apple->name = «Apple»;

PHP — instanceof

You can use the instanceof keyword to check if an object belongs to a specific class:

Источник

Classes and Objects in PHP — Basic Introduction

Abid Raza

Object-oriented Programing in PHP helps to develop big application easily with code re-usability and modularity of classes. Unlike the procedural programming, we can reuse lot’s of code for the applications when using OOP. Object-oriented programing is easy to organize, modify and debug if needed.

Let’s take look at how it goes to create classes and objects in PHP in Object Oriented Programming (OOP) style. PHP was not meant to be an object-oriented language earlier but to build a really big Web Application, definitely, you need OOP. And here comes PHP5, an Object Oriented Language.

Before we start, let’s understand some keywords often used in OOP.

Classes

We encounter objects and their behavior everywhere in the real world. Like a vehicle may have 2 wheels or four wheels . It may run on petrol or diesel and it may have different colors. It may have automated gear or manual gear etc. These can be characteristic or properties of a vehicle.

So a class is a user-defined data type, which has local methods and local data as properties. It is a blueprint for creating many objects or instances of the same type.

Objects

An object is an instance of a class. Once the class is defined, we can create many ejects of its kind having their own set of properties and behavior defined in the class blueprint.

For example , a vehicle can be two wheelers or four wheelers and have some color. to define this we create an object like vehicle1 and similarly, we can create vehicle2 also based on class Vehicle.

The difference between classes and object may be confusing if you are new to OOP. It helps to think of classes as something you create as you design your application, whereas objects are created and used when the application is actually run.

Properties

Properties, as the name suggest, are characteristics of the class. Properties are much like regular variables having a name and holds data of any type. for example, a vehicle may have color, weight etc.

Читайте также:  Php script location href

Methods

Methods in OOP defines the behavior of class which shows the actions associated with the class. We define the method using function statement in PHP. So methods are the piece of code having logic for the certain task just like the function. These are also called member function.

Creating Classes and Objects in PHP

First, let us see how to create classes, and then we will go to the explanations.

name=$string; > // name getter method public function get_name() < // return the object’s name property return $this->name; > > $john = new Person; // creating object of class Person $john->set_name("John"); // setting the name property echo "The name of our new friend is ".$john->name; // getting name property ?>

So what’s going on here! First, we are declaring the class Person with the keyword class before the class name Person. e.g. class class_name < // properties and methods >

Now here in our example above we’ve declared a property $name of the person. Next we’ve created setter and getter method for the property name, set_name() and get_name() . To refer to the property of the class in itself, you have to use $this keyword. $this keyword points to the current object.

$this->name=$string;

Note the syntax here—you use $this , followed by the -> operator. In addition, you omit the $ in front of the property you’re referring to, like this: $this->name . This is the syntax you’ll normally see in PHP OOP Programming. set_name() will be used to set the name property of the object Person and get_name() will be used to display the name. The Same syntax will be used here to call the methods of an object. e.g. $object->set_name()

Creating Objects

Next, we’ve created an object $john declared as an Object of class Person.

Syntax: $john = new Person;

After declaring the object $john, we can set the name property using the set_name() method like,

$john->set_name(“John”);

And to display name property we can use get_name() method like,

echo $john->get_name();

//or
// if the name property is declared as public access
echo $john->name;

Setting Access to Properties and methods

You can restrict access to the members of a class or object with PHP access modifiers:-

  • Public: Means “Accessible to all”
  • Private: Means “Accessible in the same class”
  • Protected: Means “Accessible in the same class and classes derived from that class”

Public Access

Public access is the most unrestricted access of all, and it’s the default. We can declare it explicitly to the properties and methods.

name=$string; > public function get_name() < return $this->name; > > $john = new Person; $john->set_name(‘John’); // this will work great echo “My name is “.$john->name; ?>

Private Access

You can make a class or object member private with the private keyword. When you make a member private, you can’t access it outside the class or object.

name=$string; > public function get_name() < return $this->name; > > $john = new Person; $john->set_name(‘John’); // this will give error echo “My name is “.$john->name; // but this will not echo “My name is “.$john->get_name(); ?>

After running this code you will see $john->name will give an error because it is declared with private access, so it will be available to only the object itself. It will prevent any accidental change in the property outside the object. This property will be not inherited by the inherent subclass and their objects. That means it will only be accessible by the class and object itself.

Читайте также:  Python string format экранирование

Protected Access

You can make a class or object member private with the protected keyword. When you make a member protected, you can’t access it outside the class or object same as private but this property can be inherited by the subclasses of this class and objects.

name=$string; > public function get_name() < return $this->name; > > $john = new Person; $john->set_name(‘John’); // this will give error echo “My name is “.$john->name; // but this will not echo “My name is “.$john->get_name(); ?>

After running this code you will see again $john->name will give an error because it is declared with protected access, so it will be available to only the object itself and the objects inheriting this class.

That’s why getter and setter methods are used to access private and protected members and to prevent any changes from outside of class of crucial information.

Construct and initialize Objects in PHP

Constructors are very convenient in both creating and initializing an object. PHP allows this with __construct() method in class. Here’s an example:-

name=$string; > function set_name($string) < $this->name=$string; > function get_name($string) < return $this->name; > > $john = new Person(“John”); echo “My name is “.$john->get_name(); ?>

In this example, we’ve created a class of person and created a constructor to initialize it with a default name. You pass data to the constructor when you use the new operator to create new objects. You can pass as many arguments to the constructor as you need, as long the constructor is set up to take those arguments.

For example: $john = new Person(“John”,” 22”, “Doctor”);

PHP classes come with a default constructor that takes no arguments, it’s the default constructor that gets called when you execute code like this: $john = new Person;

Источник

Оцените статью