PHP Create Object from Class

In this chapter you will learn:

  1. How to create object
  2. Syntax to create object
  3. Objects Within Objects

Description

A class is defining or creating a new type. We can create variables for the new type. We call it object in object oriented programming.

Syntax

We can create an object by using the following syntax:


$aRectangleObject = new RectangleClass;

We need to use the special -> operator to reference the method.


<?PHP//from   j  a  v  a 2 s  .c o  m
class Shape {
   public function say() {
      print "shape";
   }
}

$aRectangle = new Shape;
$aRectangle->say();
?>

The code above generates the following result.

Objects Within Objects

You can use objects inside other objects. Using -> to access objects within objects. For example, we could define a NameTag class and give each Book a NameTag object like this:


<?PHP//from j a v a 2s .  c o  m
class NameTag {
        public $Words;
}
class Book {
   public $Name;
   public $NameTag;
   public function say() {
      print "Book";
   }
}
$aBook = new Book;
$aBook->Name = "PHP";
$aBook->NameTag = new NameTag;
$aBook->NameTag->Words = "from java2s.com";
?>

The $NameTag property is declared like any other, but needs to be created with new once &aBook has been created.

Next chapter...

What you will learn in the next chapter:

  1. Creating and Using Properties
  2. Declaring Properties
  3. Accessing Properties
  4. Example - add properties to a class
Home » PHP Tutorial » PHP Class Definition
Concept for Object Oriented Design
PHP Class Definition
PHP Create Object from Class
PHP Class Properties
PHP Iterating Object Properties
PHP Class Inheritance
PHP Overriding Methods
PHP final Classes and Methods
PHP Abstract Class
PHP Class Access Control Modifiers
PHP Class Constructor
PHP Class Destructors
PHP Class Magic Methods