PHP Class and Objects Example

Like all other popular programming language, php also supports object oriented programming, In this tutorial, you will learn how to create class in php and php objects and properties in object oriented programming.

Before you start this tutorial you should be familiar with php basic coding syntax, here we cover topics like creating class, creating object, assigning value, reading values, adding class reference etc.

create php objects and properties

In any object-oriented programming, you need to understand how to create an object of any class, so before that, we must learn class and object concepts in php programming.

So what is class in php?

Class is programmer-defined data type, that means you as a programmer create data type as per your business need. then use that datatype in your application, let's look at the example below.

class car {            
public  $model="Not Set";
public  $color="Not Set";
public  $price=0.0;
}

In above example we have created a class (data type) called "car" .

Now we learn what is object in php?
Object is basically an instance of that class. We ceate a class once and then create many objects that belong to that class.

// cerating a new object of car class.
$maruti = new car();
              
//here is another new instance of car class.
$honda = new car();

Now let's learn how to set & get in php properties, and how to ceate an instance of php class and access properties

Ceate new file called "class_library.php" and write the following code.

<?php
class car {
public $model="Not Set";
public $color="Not Set";
public $price=0.0;
public function set_model($model_name) {
$this->model = $model_name;
}
public function get_model() {
return $this->model;
}
public function set_color($color_name) {
$this->color = $color_name;
}
public function get_color() {
return $this->color;
}
}
?>

We will access the above class from a new file called "cardetails.php" and create a new instance of above "car" class.

So at the new file write code to create a instance of car classb this way.

<?php include("class_library.php"); ?>
<?php $maruti = new car();
$honda = new car();
$maruti->set_model("Maruti");
$honda->set_model("Honda");
print_r($maruti->get_model());
?>

Notice , you can create any number of instance of same car class, in above example we have created two instance for Maruti $maruti = new car(); and Honda $honda = new car();

Then setting $maruti->set_model("Maruti"); and getting $maruti->get_model() properties of new instance Maruti

You may be interested in following php tutorials:

 
PHP Classes, objects, methods, properties
Learn php programming, php web development with free tutorials
Other Popular Tutorials
PHP Examples | Join PHP Online Course