 | News Feed |
 | Jobs Feed |
Sections
|
| feed this: |  |
Lorna Mitchell: 9 Magic Methods in PHP
by Chris Cornutt December 11, 2012 @ 12:18:49
Lorna Mitchell has a new post showing nine of the magic methods that are included in PHP by default (like __construct, __get and __set) including a few you may not have used before.
The "magic" methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events. That might sound slightly automagical but actually it's pretty straightforward, we already saw an example of this in the last post, where we used a constructor - so we'll use this as our first example.
She includes details (and some code samples) for these methods:
- __construct
- __destruct
- __get
- __set
- __call
- __sleep
- __wakeup
- __clone
- __toString
You can find out about these and a few others in this page of the PHP manual.
voice your opinion now!
magic methods oop introduction beginner tutorial
Michael Maclean: Why one-line installers are a bad idea
by Chris Cornutt September 21, 2012 @ 11:35:29
There's a feature that's usage has been showing up more and more in software projects (both open source and not) that allows you to install their system with a single line command, usually involving curl and maybe piping it to a shell. In this recent post Michael Maclean takes a look at this trend and some of the possible pitfalls of the approach.
There has been a trend in the last while for various bits of useful software to have a one-line shell command recommended as the installation method. The usual form of this is to pipe something like curl or wget to some interpreter, be it bash, php, ruby, or some such. [...] This [type of] command takes the output of curl and pipes it straight to bash. I have several issues with this.
His three main points center around the fact that you cannot inspect the code before executing it with this method, that you can't verify the source of the code and that it teaches users bad habits of trusting in "magic commands" like these.
voice your opinion now!
installer oneline opinion curl bash shell magic
Pim Elshoff's Blog: In favour of typing
by Chris Cornutt April 25, 2012 @ 13:57:38
Pim Elshoff has a new post to his blog that shares his preference on typing (keystrokes, not variables) in applications (hint: he likes it):
We sometimes conceive of ideas that are arduous to express in code. Like persisting data, or some other uncommon task (sarcasm). It's not difficult, but it takes a lot of keystrokes to write. Being problem solvers, we find it difficult doing this kind of manual labour, especially when machines can do it for us. Still, I would like to take this opportunity to say that typing rocks and solutions that save typing suck.
He talks about the abstraction that frameworks provide (less typing, more work) and and some of the "magic" that comes with them. He gives specific examples of some of his pervious experience with frameworks (including some pains with Symfony2) and how some of the magic he's seen is easy to write but hard to read.
voice your opinion now!
favor typing keystrokes framework magic opinion
Refulz.com: The __toString() Method - Objects as Strings
by Chris Cornutt February 09, 2012 @ 09:27:19
On the Refulz.com blog there's a recent post introducing the __toString() magic method in PHP. This handy method allows you to define how to return an object when it's referenced as a string.
We started the study of PHP magic methods by learning about __get() magic method. [...] PHP is loosely typed language and same variable can be used or referred as string, number or object. The __toString() method is called when the code attempts to treat an object like a string. This function does not accept any arguments and should return a string.
Some quick code is included showing how it works - returning a combined string made from two private class properties when the object ($obj) is echoed out. They also show multiple ways of using the method in both pre- and post-PHP 5.2.
voice your opinion now!
tostring magic method object string
Bence Eros' Blog: Getters, setters, performance
by Chris Cornutt July 12, 2011 @ 11:39:18
Bence Eros has put together a new post to his blog looking at some of the results he's found from performance testing the use of getters and setters in PHP.
The usage of getter and setter methods instead of public attributes became very popular in the PHP community, and it's going to become the standard coding convention of so many PHP libraries and frameworks. On the other hand many developers - including me too - strongly unrecommend such convention, because of its performance overhead. I wanted to make some performance comparison for years, and today I had time to do that. In this post I would like to show what I found.
He starts with a question every developer asks as their working in their application - why and when should they use getters and setters for their classes. He talks about using them as primary functionality or as fallbacks only when needed. He includes the simple benchmarking script he used to compare accessing/setting public attributes directly and using a getter/setter to do the same. The results aren't very surprising if you think about the "magic" that has to happen for getters and setters to work. See the rest of the post for those numbers.
voice your opinion now!
getter setter performance benchmark compare magic
Web Developer Juice: PHP Magic Functions Best Part of Object Oriented PHP - Part 1
by Chris Cornutt May 03, 2011 @ 11:57:08
On the Web Developer Juice blog there's a recent post, the first part in a series looking at one of the more handy features of the recent releases of PHP - the magic functions (some which were added in the PHP 5.x series).
There are some reserved function names in PHP class starting with __ ( double underscore ). These are __construct, __destruct, __isset, __unset, __call, __callStatic, __sleep, __wakeup, __get, __set, __toString, __set_state, __invoke and __clone. You cannot use these functions to serve your logical purpose but these are meant to be used for providing magic functionality.
They go through some of the above methods and talk about what role they can play in your code and, for some, a brief bit of code to explain how it works. This first part covers __construct/__destruct and __call/__callStatic.
voice your opinion now!
objectoriented oop magic method tutorial
Matthew Weier O'Phinney's Blog: Dependency Injection An analogy
by Chris Cornutt March 22, 2011 @ 12:36:20
For those still grappling with the concept of dependency injection, Matthew Weier O'Phinney has posted an analogy that could help make the concept a bit more clear.
I've been working on a proposal for including service locators and dependency injection containers in Zend Framework 2.0, and one issue I've had is trying to explain the basic concept to developers unfamiliar with the concepts -- or with pre-conceptions that diverge from the use cases I'm proposing.
Using his wife as a sample sounding board, he came up with a restaurant-based analogy to help explain the concept - asking for certain pre-planned things but wanting customizations. He reminds developers that there's not much "magic" to DI. Things are all well defined from the outset and you only have to use it when you want.
voice your opinion now!
dependency injection analogy restaurant magic configuration
Jose da Silva's Blog: Revisiting PHP 5.3 __invoke magic method
by Chris Cornutt November 05, 2010 @ 12:42:04
In a new post to his blog Jose da Silva briefly looks at a feature that was introduced in the PHP 5.3.x series of the language - the __invoke magic method.
PHP version 5.3 introduced a new magic method designed __invoke, this method is called when a script tries to call an object as a function. [...] As php cannot accommodate pseudo-first-class functions, the __invoke method can be used to suppress this language limitation. On other hand you can use this for simpler things as pass a function around.
He includes a simple code example that shows a basic class being called via a variable name - $c('ford') - and the result of its __invoke method being called. He notes that the method, in his opinion, could make for less clean code.
voice your opinion now!
invoke magic method opinion example
NETTUTS.com: Deciphering Magic Methods in PHP
by Chris Cornutt July 20, 2010 @ 13:27:44
Whether you're new to the language or to the more advanced features of it, you might find the magic methods a bit confusing at first. Thankfully, NETTUTS.com is here to help with this new tutorial on what they are and how to use them in your code.
PHP provides a number of 'magic' methods that allow you to do some pretty neat tricks in object oriented programming. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met. Magic methods provide some extremely useful functionality, and this tutorial will demonstrate each method's use.
They define a sample class so you can see them in context - a Device and a Battery. They cover constructors/destructors, get/set, isset/unset, toString, clone and more (including the callStatic that's only in the recent PHP 5.3 versions of the language).
voice your opinion now!
magic method tutorial introduction
Think Vitamin: 9 Magic Methods for PHP
by Chris Cornutt June 07, 2010 @ 13:58:41
For those just getting started with PHP and wondering what these "magic methods" are all about (and they can be a little confusing for someone not used to the language), Lorna Mitchell has a new tutorial posted to the Think Vitamin blog on just that topic.
The "magic" methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events. That might sound slightly automagical but actually it's pretty straightforward, we already saw an example of this in the last post, where we used a constructor - so we'll use this as our first example.
She talks about nine of these magic functions including:
- __get/__set for variable handling
- __sleep/__wakeup for serializing data
- __call/__callStatic for methods in a class
- __construct/__destruct for making and destroying classes
voice your opinion now!
magic method tutorial oop
DevShed: The Destruct Magic Function in PHP 5
by Chris Cornutt June 24, 2009 @ 08:46:18
DevShed has posted the second to last part of their tutorial series looking at the magic functions in PHP. This time they focus on the destruct function, a method that is fired off when an object is being removed from memory.
There are a few [other methods] that can be really useful for performing relatively complex tasks with a minimal amount of code. That's exactly the case with the "__destruct()" method, which will be called automatically by the PHP engine before destroying an instance of a particular class at the end of a script.
They update their example class with a new __destruct method that takes the user information inserted previously, serializes it and drops it into the current session.
voice your opinion now!
tutorial function magic destruct
DevShed: The Autoload Magic Function in PHP 5
by Chris Cornutt June 23, 2009 @ 07:56:57
DevShed has posted the latest article (the last) in their series looking at the "magic functions" that PHP has to offer. This time they take a closer look at the autoload functionality.
PHP 5 offers yet another magic method that can be extremely useful for loading classes automatically, without having to use explicitly any "include()/include_once()" or "require()/require_once()" function. As the article's title suggests, I'm talking specifically about the "__autoload()" function, which deserves a deeper analysis.
Their example shows how to define the __authoload method for your application to load in libraries as they're needed, without having to specifically define them.
voice your opinion now!
tutorial function magic autoload
DevShed: The Sleep and Wakeup Magic Functions in PHP 5
by Chris Cornutt June 17, 2009 @ 08:49:19
DevShed has posted the next part of their series looking at the "magic functions" that PHP5+ has to offer you in your development. They've already looked at ones like __call, __clone and __isset/__unset and now, with this new tutorial they've added __sleep and __wake.
Magic functions are an important part of the numerous improvements and additions that were introduced originally in PHP 5. They can be extremely handy when it comes to simplifying the execution of complex tasks. [...] In this fourth chapter I'm going to examine closely the "__sleep()" and "__wakeup()" functions, which are called automatically when an object is serialized and unserialized respectively.
In their example code they add the __sleep and __wake functions to the class they've been developing to output a string when the object is manipulated. These methods are automatically called when a serialize/unserialize function call is made on the object.
voice your opinion now!
tutorial function magic wakeup sleep
DevShed: Using the Clone Magic Function in PHP 5
by Chris Cornutt June 15, 2009 @ 12:04:25
New on DevShed today is the latest article in their "magic functions" series. This time they focus on the "clone" method to create exact copies of current objects.
In this fifth part of a seven-part tutorial on magic functions, we'll briefly review the sleep and wakeup functions, and then tackle the clone function. [...] So, with that goal in mind, in this fifth part of the series I'm going to take a closer look at the "__clone()" method, which as its name suggests, is called behind the scenes when using the "clone" PHP keyword.
Their example code adds on to the previous examples using "__get" and "__set" and adds in a method to catch the cloning of an object. It only outputs a string ("Cloning user object") when its called, but it lets you get the idea.
voice your opinion now!
method magic tutorial clone
DevShed: The Call Magic Function in PHP 5
by Chris Cornutt June 09, 2009 @ 08:44:57
Continuing their look at the "magic functions" that are included in PHP5, DevShed has posted this new tutorial looking at the "__call" method to intercept calls to methods in a class that don't exist.
If you're a PHP developer who wishes to learn how to implement and use the set of magic functions that come included with PHP 5, you've come to the right place. [...] As the title of this article suggests, in the new few lines I'm going to take a deeper look at the"__call()" function, so that you can quickly become familiar with it.
They include code examples of the __call method in use - catching a call to a "fetch" method.
voice your opinion now!
tutorial call function magic
DevShed: Magic Functions in PHP 5
by Chris Cornutt May 27, 2009 @ 08:42:38
In this new tutorial on DevShed they take a look at a feature added in PHP5 to help makes developers' lives easier - magic functions. These magic functions (like __get and __set) can help you catch things a bit closer to the execution of the language than an if or other conditional could and to do some very fun things.
It's not breaking news that the release of PHP 5 drastically changed the way that many developers build their web-based programs. The incorporation of a much more robust object model, along with the introduction of native exceptions, type hinting and so forth (add your own improvement to the list) has given the language the maturity that we see in it today. This seven-part article series will explain an important new feature: magic functions.
This first part of the series looks at __get and __set and how to use them for property overloading in a class.
voice your opinion now!
tutorial function magic
Packt Publishing: PHP Magic Features
by Chris Cornutt April 14, 2009 @ 09:31:48
Packt Publishing has posted a new article from Jani Hartikainen about the "magic methods" that PHP comes with - methods, properties and constants really.
Magic methods, which are class methods with specific names, are used to perform various specialized tasks. They are grouped into two: overloading methods and non-overloading methods. [...] Magic functions, which are similar to magic methods, but are just plain functions outside any class. [...] Magic constants, which are similar to constants in notation, but act more like "dynamic" constants. We'll also look at some practical examples of using some of these, and lastly we'll check out what new features PHP 5.3 is going to add.
He looks at the various functions/methods and constants (like __clone, __toString), some of the overloading methods like __call, and magic constants like __FILE__ and __CLASS__. He wraps it up by briefly discussing what PHP 5.3 adds in - a few new magic methods and constants (but no functions).
voice your opinion now!
magic features php5 constant function method
Cormac's Blog: Read-only object variables in php using magic methods
by Chris Cornutt January 23, 2009 @ 12:09:51
This new post on Cormac's blog shows a little trick you can use to make "read-only" object variables with the help of the handy magic methods built in to PHP5.
You can create read-only object variables by using the "private" keyword and the __get() and __set() magic methods. [...] So now classWithReadOnlyVar::readOnlyVar is only settable from inside the class, but you can read it from anywhere.
His example code initially sets up the read-only variable as a property of the example class. The __get magic method is called to correctly fetch the value but the __set intercepts anything trying to change its value. This same sort of thing can be accomplished with the protected/private keywords in PHP5.
voice your opinion now!
readonly object variable magic method example
Arpad Ray's Blog: The adventure of PHP and the magic quotes
by Chris Cornutt December 17, 2008 @ 12:03:07
One of the things that's been hanging around PHP's neck since its early days is the magic_quotes setting that was introduces to try to make things easier. In this interesting post Arpad Ray takes a look at this setting and why its a bad thing for PHP to have around.
Like register_globals, it helped lower the barrier of entry to building a dynamic website by removing some of the complexity. However it certainly wasn't without sacrifice, problems with the implementation quickly appeared and continued to abound for the next ten years. Finally in PHP 5.2.2 we got an implementation which (as far as its intentions went) seemed to be bug free, but of course by then it was turned off by default and was already slated to be dropped in PHP 6.
He looks at a few reasons they're bad (not good enough for escaping, inconsistent, performance issues) and some methods - code snippets - on how to deal with it being turned on on your server.
voice your opinion now!
adventure magic quotes bad php5 php6 fix
SaniSoft Blog: The prefix automagic in CakePHP routing
by Chris Cornutt April 09, 2008 @ 13:06:18
On the SaniSoft blog, Tarique Sani talks briefly about some of the prefix "automagic" that's already built in to the CakePHP framework's routing.
There are times when you need more than just admin routing, how about something like http://blah.com/user/profiles/edit and http://blah.com/user/profiles/changepassword ? If this could be routed to an action like user_add and user_changepassword wouldn't it be great!! (eg: think ownership ACL checks)
Good thing the CakePHP developers already planned for something like this - they included the connect() method for Router objects that maps the URL request to a method with that same prefix in the controller.
voice your opinion now!
cakephp framework prefix routing magic connect
Lars Strojny's Blog: New magic constant in PHP 5.3
by Chris Cornutt February 22, 2008 @ 15:02:00
In this new blog post today, Lars Strojny talks about a new magic constant that will be joining its brothers in the upcoming PHP 5.3 release - __DIR__.
In PHP 5.3 there will be another magic constant __DIR__. [...] To allow this, the internal function php_dirname() has been moved in the Zend Engine and is now called zend_dirname(). Nevertheless an alias still exists.
__DIR__ will join the other constants (like __LINE__ and __FUNCTION__) to help give the currently running script a little introspection for things like its filename, what class it's currently in and now, what directory the file currently lives in.
voice your opinion now!
dir magic constant directory php5 new
Larry Garfield's Blog: Benchmarking magic
by Chris Cornutt November 08, 2007 @ 12:04:00
Larry Garfield has put together some benchmarks based around a request he had from other developers (the "performance czars") as to how the magic functions in PHP5 would perform in the new environment.
Already, there is talk of how, and if, to leverage PHP 5's object handling now that we don't need to deal with the weirdness of PHP 4's object model. Of course, because it's Drupal, our army of performance czars want to know just what the cost is for object handling, and especially advanced object magic like __get(), __call(), the ArrayAccess interface, and so forth.
He an his tests on a Thinkpad (Intel Core2 Duo 2.2Ghz) running Kubuntu and PHP 5.2.3. They were run two million times benchmarking the different methods for:
- function calls
- __call
- __get
- __set
- iterators (array)
- inheritance
- composition
His results are listed at the end of the post.
voice your opinion now!
benchmark magic function get set call iterator inheritance composition benchmark magic function get set call iterator inheritance composition
Chris Cassell's Blog: Creating Magic Methods in PHP
by Chris Cornutt August 13, 2007 @ 10:21:00
In this new entry to his blog today, Chris Cassell shows how to create "magic methods" - ones that make use of overloading to do special things.
I've learned a lot of things from various open source frameworks, especially CakePHP. One of the most impressive things about Cake, and Ruby on Rails for that matter, is its magic methods in its data model class [...] I've implemented similar methods in the home-grown framework that I use at work. Here's how to do it.
In his example, he gives both the PHP4 and PHP5 code to make a simple magic method class with a __call() function to handle undefined method calls. Using this, he maps a undefined method call to another method in the class (called findAllByColor and mapped to findAll with the right parameters).
voice your opinion now!
tutorial magic method class php5 php4 cakephp framework tutorial magic method class php5 php4 cakephp framework
WebReference.com: The Building Blocks Data Types, Literals, Variables, and Constants - Part 3
by Chris Cornutt January 29, 2007 @ 11:44:00
WebReference.com has posted part three of their "Building Blocks" series - a look at data types, literals, variables, and constants.
In part three, they focus more on the last type of "block" in their list - the constant:
Some real-world constants, such as pi, the speed of light, the number of inches in a foot, and the value of midnight, are values that don't change. PHP not only provides its own predefined constants but lets you create your own. Using constants makes it easy to write and maintain your programs.
There's talk of the define() and constant() functions and a mention of some of the predefined and "magic constants" as well.
voice your opinion now!
building blocks variable constant define magic building blocks variable constant define magic
php|architect: The Magic __set_state Method
by Chris Cornutt July 21, 2006 @ 07:03:00
On php|architect's A/R/T article repository today, there's this new tutorial centered around the use of the "magic" method __set_state in PHP5.
It is fairly self-evident how to use most of the magic methods of PHP 5. However, it is not quite so apparent how to use the __set_state method introduced in PHP 5.1. In this article, Peter lavin delves into this elusive magic method to show you how to use this gem in some really 'classy' object oriented PHP.
The author (Peter Lavin) talks first about what magic methods are and, specifically, what the __set_state method can do. He gives an example, comparing a normal usage of var_export to functionality using __set_state.
voice your opinion now!
magic method __set_state var_export tutorial magic method __set_state var_export tutorial
Greg Beaver's Blog: phpDocumentor and __get/__set/__call - give us your ideas (RFC)
by Chris Cornutt July 14, 2006 @ 06:06:00
In his latest post today, Greg Beaver is also taking a look at phpDocumentor and some of the documentation methods it allows, noting that providing the right notes on the "magic" functions has always been a point of difficulty.
One of the trickier feature requests for phpDocumentor has been documenting "magic" object properties and methods. By "magic" I am referring to properties and methods that are created dynamically by PHP 5.0+ userspace class methods __get, __set, __isset, __unset and __call.
He gives a code example of creating properties and a magic function (borp). To illustrate his point, he tries to specify the phpDocumentor format that would go with it - not an exact match, but with the help o ffour new tags it's made easier: @property, @property-read, @property-write, and @method.
voice your opinion now!
phpdocumentor __get __set __call ideas magic functions property phpdocumentor __get __set __call ideas magic functions property
Professional PHP Blog: PHP Games
by Chris Cornutt April 07, 2006 @ 06:52:42
From the Professional PHP site today, there's an interesting new post about a game the author found (via digg) of "Heroes of Might and Magic" online minigame. What makes it even cooler? It's written in PHP and uses Prototype and Scriptaculous for the interface.
The interface is very drag and drop oriented and it uses Ajax to update game status. The graphics are very good. No flash as far as I can tell.
Their server is getting crushed right now, intermittently not responding and running out of MySQL connections. The javascript crashed my browser a couple times. Still, I was intrigued by the combination of Ajax and PHP and I liked the interface. Definitely one to bookmark for later.
The game is a bit less overloaded now, but still a bit slow. The interface is wonderfully done, and easy to understand. It's great to see the popular pairing of Ajax and PHP starting to show up in commercial applications, too.
voice your opinion now!
game ajax heroes of might and magic minigame prototype scriptaculous game ajax heroes of might and magic minigame prototype scriptaculous
WebReference.com: How to Interact with Web Forms (Part 1)
by Chris Cornutt January 18, 2006 @ 07:13:05
On WebReference.com today, there's this new tutorial with an introduction to getting PHP to interact with web forms.
HTML forms are one of the key ingredients of any dynamic website because they can enable the users of a site to interact with it. Otherwise, websites are more or less static:They may be driven by a database and, therefore, regularly changing, but they look the same for each and every visitor. HTML forms can change that; therefore, using data from forms from within PHP is very important.
They give examples of how to send data back to a script from a form, reading that data (using superglobals), and what data will be returned from each form element type. From there, they get into specifics like dealing with magic quotes and saving the form data into a cookie...
voice your opinion now!
interact web forms superglobals types magic qutotes cookies interact web forms superglobals types magic qutotes cookies
|
Community Events
Don't see your event here? Let us know!
|