PHP Create Object from Class
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// w ww . j a va2 s . co 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/* w ww . j a v a 2 s . c om*/
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.