Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

Creating an Object

It’s much easier to create objects and use them than it is to define object classes, so before we discuss how to define classes, let’s look at creating objects. To create an object of a given class, use the new keyword:

$object = new Class;

Assuming that a Person class has been defined, here’s how to create a Person object:

$rasmus = new Person;

Do not quote the class name, or you’ll get a compilation error:

$rasmus = new 'Person';                 // does not work

Some classes permit you to pass arguments to the new call. The class’s documentation should say whether it accepts arguments. If it does, you’ll create objects like this:

$object = new Person('Fred', 35);

The class name does not have to be hardcoded into your program. You can supply the class name through a variable:

$class = 'Person';
$object = new $class;
// is equivalent to
$object = new Person;

Specifying a class that doesn’t exist causes a runtime error.

Variables containing object references are just normal variables—they can be used in the same ways as other variables. Of particular note is that variable variables work with objects, as shown here:

$account = new Account;
$object = 'account'
${$object}->init(50000, 1.10);  // same as $account->init
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Programming PHP, 2nd Edition

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata