php 5 magic methods

54
PHP 5 Magic Functions Front Range PHP Users Group http://frontrangephp.org/ February 10, 2010

Upload: david-stockton

Post on 25-May-2015

12.378 views

Category:

Technology


1 download

DESCRIPTION

A brief overview of magic methods/functions in PHP 5 along with sample usage.

TRANSCRIPT

Page 1: PHP 5 Magic Methods

PHP 5 Magic FunctionsFront Range PHP Users Group

http://frontrangephp.org/

February 10, 2010

Page 2: PHP 5 Magic Methods

PHP 5 Magic Functions

All functions start with __PHP reserves all function names starting

with __Don’t define them unless you want the

magic functionality

Page 3: PHP 5 Magic Methods

Magic Methods in this Presentation

__construct()__destruct()__toString()__get()__set()__isset()__unset()__call()__clone__set_state()

Page 4: PHP 5 Magic Methods

Magic Methods briefly covered

__callStatic()__sleep()__wakeup()__invoke()__autoload()

Page 5: PHP 5 Magic Methods

New to PHP 5

Magic functions (in general) allow you to define class functionality without needing to duplicate code

I say in general since some of them don’t really seem to follow that definition and I didn’t find a definition that covers them all.

Page 6: PHP 5 Magic Methods

__construct()

If you’ve done any OOP in PHP5, you’ve probably run into this method.

Used to initialize an object.Best practices say to make sure you don’t

do work in the constructor.Just assign values… and remember Dependency Injection

(coming up next)

Page 7: PHP 5 Magic Methods

__construct()

Constructor is setting values, but not doing work

Page 8: PHP 5 Magic Methods

__construct()

Doing work in constructors makes it harder to reuse the class.

Page 9: PHP 5 Magic Methods

__construct()

If you don’t provide a constructor method, and extend a class, the parent constructor will be called automatically.

If you do provide a constructor, and want the parent constructor called, you must called parent::__construct()

Page 10: PHP 5 Magic Methods

__construct()

By making the constructor inaccessible, you can prevent external instantiation.

For example, implementing the singleton pattern, we don’t want external instantiation since we cannot control how many objects are created.

Page 11: PHP 5 Magic Methods

__destruct()

__destruct() is called when ◦all references to an object are removed◦object is explicitly destroyed◦shutdown sequence is initiated

Page 12: PHP 5 Magic Methods

__destruct()

Parent destructors must be called explicitly if destructor is provided

Page 13: PHP 5 Magic Methods

__destruct()

You could use this method to ensure an object logs itself.

Page 14: PHP 5 Magic Methods

__destruct()

The destructor is called even if a script exits due to a call to exit()

However, if you call exit() in a destructor, the other destructors will be skipped.

Throwing an exception in the destructor is a fatal error.

Page 15: PHP 5 Magic Methods

__toString()

Called whenever you try to use an object in a string context

Page 16: PHP 5 Magic Methods

__toString()

Page 17: PHP 5 Magic Methods

__toString()

You can invoke via echo, print, *printfCast to string

$var = (string)$obj;

Page 18: PHP 5 Magic Methods

__toString()

__toString() cannot throw an exception – results in a fatal error

If you call functions or methods in your __toString() that can throw an exception, make sure you handle it within the __toString() method

Page 19: PHP 5 Magic Methods

__get()

Called when code tries to access non-accessible properties

Page 20: PHP 5 Magic Methods

__get()

Non-accessible can mean either the property is not defined or that it is not public

If it’s not defined, then __get() will be called from both inside and outside of the class context

Page 21: PHP 5 Magic Methods

__get()

Page 22: PHP 5 Magic Methods

__get()

Page 23: PHP 5 Magic Methods

__get()

Classes don’t even have to have properties

Page 24: PHP 5 Magic Methods

__get()

You could even use it to process values…

Page 25: PHP 5 Magic Methods

__set()

Called when code tries to set a property that is not accessible.

Not accessible can mean not defined or not public

Page 26: PHP 5 Magic Methods

__set()

Page 27: PHP 5 Magic Methods

__set()

If __set() is used to set a property that doesn’t exist, the new property will be public.

If it is used on a property that is not public, the accessibility will not change

Page 28: PHP 5 Magic Methods

__set()

Use it to validate values as they are passed in

Page 29: PHP 5 Magic Methods

__set()

If you want only the values you defined to be used in a class, set that behavior in __set().

Page 30: PHP 5 Magic Methods

__isset()

Called when isset() is called on an inaccessible property

If you’re using __set() and __get(), not defining __isset() can lead to some really weird errors.

Page 31: PHP 5 Magic Methods

__isset()

Page 32: PHP 5 Magic Methods

__isset()

How can this be?You can retrieve the value, but it’s not

set?

Must define __isset()

Page 33: PHP 5 Magic Methods

__unset()

Called when code tries to unset a non-accessible value.

Without __unset()

Page 34: PHP 5 Magic Methods

__unset()

With __unset()

Page 35: PHP 5 Magic Methods

__call()

Called when a method is called that is not accessible.

Page 36: PHP 5 Magic Methods

__call()

Use it to extend a class and make everything public…

Page 37: PHP 5 Magic Methods

__call()

Yes, I didn’t extend anything in that example, but the principle is the same

Page 38: PHP 5 Magic Methods

__call()

Virtual Getters and Setters

Page 39: PHP 5 Magic Methods

__call()

All sorts of other uses for __call()

Page 40: PHP 5 Magic Methods

__clone()

Used if custom clone() behavior is neededIf clone() is called on an object that

contains other objects, both the clone and the original contain the same objects.

Define __clone() to define what happens when an object is cloned

Page 41: PHP 5 Magic Methods

__clone()

Default Clone behavior

Using === to show they are the same

Click icon to add picture

Page 42: PHP 5 Magic Methods

__clone()

Now with custom __clone()

Page 43: PHP 5 Magic Methods

__clone()

In the previous example we are comparing the objects

Even if the number value is the same, there are still two different objects

Page 44: PHP 5 Magic Methods

__set_state()

Used to set the state of an object when var_export code is used.

Page 45: PHP 5 Magic Methods

__set_state()

var_export() creates runnable PHP code.

So what happens when we run it?

Page 46: PHP 5 Magic Methods

__set_state()

So let’s define it

Page 47: PHP 5 Magic Methods

__set_state()

Why the differences?◦stdClass doesn’t have a __set_state()◦Since $val is protected, I need a setter.◦Plus it shows how to deal with non-public stuff

Page 48: PHP 5 Magic Methods

Brief Look at other magic methods

You’ve already seen 48 slides, and chances are it’s getting close to an hour…

So here’s a quick overview of a few more of the magic methods

Page 49: PHP 5 Magic Methods

__callStatic()

New in PHP 5.3Very similar to __call()Intended for when a method is called in a

static context (inaccessible method)

SomeClass::protectedStaticMethod();

Page 50: PHP 5 Magic Methods

__sleep()

Called when an object is serialized with PHP’s serialize.

Can be used to shutdown and remove resources (like database connections) which cannot be serialized

Page 51: PHP 5 Magic Methods

__wakeup()

Called when an object is unserialized.Can be used to re-establish connections

and re-initialize resourcesie, reconnect to the database

Page 52: PHP 5 Magic Methods

__invoke()

New in PHP 5.3Allows you to treat an object like a

function

Page 53: PHP 5 Magic Methods

__autoload()

Everyone using PHP 5 should be using this, or at least some form of autoloading.

Allows you to automatically load PHP files when they are needed.

No more need for require_once or include_once in your scripts

Page 54: PHP 5 Magic Methods

Q & A

Any questions?