Objects in PHP


Share

Objects are real world entities, and the collection of objects is called Class.
When creating a program to use objects, you need to design a composite of data and code called a class.
Each new object based on this class is called an instance (or occurrence) of that class.
The data associated with an object are called its properties; the functions it uses are called methods.
When creating objects, it is best to use encapsulation, or writing a class in such a way that only its methods can be used to manipulate its properties.


1) Declaring a Class

Before you can use an object, you must define a class with the class keyword.
Class definitions contain the class name (which is case-sensitive), its properties, and its methods.

<?php
$object = new User;
print_r($object);
class User
{
  public $name, $password;
    function save_user()
    {
     echo "Save User code goes here";
    }
}
?>

2) Creating an Object

To create an object with a specified class, use the new keyword, like this: $object = new Class

<?php
$object = new User;
$temp   = new User('name', 'password');
?>

3) Accessing Objects

<?php
$object = new User;
print_r($object);
$object->name     = "Joe";
$object->password = "mypass";
print_r($object);
  $object->save_user();
    class User
    {
        public $name, $password;
        function save_user()
        {
                   echo "Save User code goes here";
        }
    }
?>

As you can see, the syntax for accessing an object’s property is $object->property.
Likewise, you call a method like this: $object->method().
You should note that the property and method names do not have dollar signs ($) in front of them.

4) Cloning objects

<?php
$object1       = new User();
$object1->name = "Alice";
$object2       = clone $object1; 
bject1; $object2->name = "Amy";
echo "object1 name = " . $object1->name;
echo "object2 name = " . $object2->name;

class User
       {   
        public $name;
       } 
?>
<?php OUTPUT: object1 name = Alice object2 name = Amy ?>