News Feed
Jobs Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

James Fuller's Blog:
Enforcing contracts in your PHP functions and methods
March 23, 2012 @ 08:37:11

James Fuller has a new post to his blog today about a way you can enforce contracts in your PHP using a combination of type hinting and value checking.

Design by contract is an important concept for controlling what type of input your methods or functions can receive. One of the most dangerous features of PHP is that functions will still execute even when they are missing required arguments, by emitting a warning instead of an error. In this post, I am going to walk through some of the solutions available to deal with this problem.

He shows how to alter a basic function to first use type hinting to catch when a variable is the wrong type (in this case checking for an array and stdClass) which causes a Fatal error and makes the function not execute. He includes sample code for the type/value checking option and also includes a suggestion of using PHPUnit's assertions as another option.

Finally, he introduces the ContractLib tool (from Stuart Herbert) that makes use of closures to enforce checks - his example checks to see if something is a string and that it's not empty.

0 comments voice your opinion now!
enforce contract function exception typehint contractlib


blog comments powered by Disqus

Similar Posts

Dikini.net: Poor man's macro programming in php

Felix Geisendorfer's Blog: A PHP developers guide to JavaScript - Part 1

PEAR Blog: PEAR Group Meeting Minutes 2008-07-13

Gonzalo Ayuso's Blog: Checking the performance of PHP exceptions

Vexxhost.com: Top 5 new (and cool!) features in PHP5 that you probably haven't heard of


Community Events











Don't see your event here?
Let us know!


composer symfony2 release hack language example introduction hhvm unittest facebook database component project application package framework security performance podcast install

All content copyright, 2014 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework