Archive for the 'PHP' Category

September 11th 2007

Auto Converting PHP Objects to Strings using the __toString() ‘Magic Method’

Ever wished there was a way to echo or print a PHP Object as if it were just a string and have it print something more usefull than Object id #1? In PHP5+ there is a Magic Method __toString() that will allow you to specify how you want your Object to react when converted to a string.

<?php
class Person{
  private $firstName="Brien";
  private $lastName="Wankel";
  private $age="30";
  ...
  public function __toString(){
      return "{$this->firstName} {$this->lastName}";
  }
}
$me = new Person();
echo("My name is {$me}"); // prints: My name is Brien Wankel
?>

No Comments yet »

January 26th 2007

An easier way to do simple matches with PHP

Tired of trying to figure out that perfect Perl-style regular expression when all you need to do is a simple match? Well, toss away that ereg or preg_match call you’ve been working on for the last 20 minutes and use your new friend fnmatch(). fnmatch will let you match using POSIX shell command style patterns, which may be much much easier for a non regex guru to wrap their head around.

<?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?>

This function is only available on POSIX compliant systems, so all you Windows PHP users are out of luck.

Enjoy!

2 Comments »

December 20th 2006

Marco Tabini: 5 PHP Performance Tips You Probably Don’t Want To Hear

From Marco Tabini’s blog, also available in the Dec. issue of php|architect

Search the Internet—Google or no Google—and you’ll find a number of “top five lists” of tips to improve the performance of your code. Most of these lists promise you the developer’s version of all gain and no pain: performance increases without the need for any changes to your code. Some of the suggestions are too good to be true, some are just plain wrong, and some will yield some modest form of performance increase.

Installing an opcode cache, however, is not going to save you from the depths of Hell when you’re trying to run a complex select statement over a table with ten million records and no indices, however. With all these “get performing quick” articles floating around the Web, I thought it might be interesting to write an article about the performance-enhancing tips you probably don’t want to hear about—that is, those that are most likely to produce measurable (and durable) results but do require some effort on your part.

Go to Marco’s blog to read the tips

No Comments yet »

November 20th 2006

Suppress errors in PHP function calls

Some run-time errors in PHP may cause sensitive information to be output to the browser. PHP provides as special operator, called the error suppression operator (@), as a way to stop these errors from being displayed. By placing ,@ before a function call, most errors will be suppressed. I say most because this operator will only suppress errors that for functions that use PHP’s built in error reporting functionalities.

For more information, check out the Error Control Operators section of the PHP manual.

No Comments yet »

November 14th 2006

Fun With Flickr Feeds

Flickr has some really great web services, one of the easiest to use is the feeds service. To grab a set of data from flickr in XML format, just open the following URL in your application:
http://api.flickr.com/services/feeds/photos_public.gne?tags=[comma separated tags here]

by default, the feeds are returned in “plain” XML format, to make things more interesting you can specify a format parameter

prefer PHP data? just:

<?php
  include_once("http://api.flickr.com/services/feeds/\
                    photos_public.gne?tags={$tags}&format=php");
  // broken up to fit format, but in practice leave this as one line
  // i now have a $feed array set with all the feed data:
  print_r($feed);
?>

or perhaps json:
to use the json (in javascript) you must first define a function called jsonFlickrFeed which takes in one object. This object will be your flickr feed data, then below that in your HTML head, you include the feed url as a javascript src file:

  <head>
    <title>Flickr Testbed</title>
    <script type="text/javascript">
      var photos = null;
      function jsonFlickrFeed(feedData){
        photos = feedData;
      }
    </script>
    <script type="text/javascript" src="http://api.flickr.com/services/feeds/\
            photos_public.gne?tags=toothbrush,red&format=json">
    </script>
  </head>
...

to view all the other feed formats, check out the formats section of the Flickr Feeds page.

No Comments yet »

October 24th 2006

Print_r to a String

Every PHP developer knows about the print_r function, but for some reason, not many of them know that you can capture the output of print_r and avoid it being printed directly to stdout (the browser in most cases). The print_r function has a little know second argument, true or false, which tells it what to do with the output. By default this is false, which means “don’t return, print to stdout”, if you set this to true, print_r will return a string, which you can do whatever you want with.

<?php
  $o = new stdclass();
  $o->name = "brien";
  $o->website = "http://code-a-day.com/";
  $o->date = "today";
  print_r($o); // prints to stdout (the browser window)
  // a common thing i do is print to the error log:
  error_log( print_r($o, true) ); // prints to the default apache error log
  // save it in a variable
  $data = print_r($o, true);
?>

No Comments yet »

October 22nd 2006

PHP5 and the SPL - Pt1: ArrayObjects

With the Standard PHP Library (SPL) available in PHP5 a new object is available to make arrays a little more usefull. Java developers wanting to learn PHP will find comfort in PHP’s ArrayObject.

to create an array object, just new it:

<?php
  $arrayObj = new ArrayObject();
  // or create one from an existing array:
  $normal_array = array();
  $normal_array[]  = "item one";
  $normal_array[] = "item two";
  $normal_array[] = "item three";
  $arrayObj = new ArrayObject($normal_array);
?>

to add and access data, it’s super easy:

<?php
  $arrayObj->append("item four");
  $arrayObj->offsetGet(3); // get the value at offset 3
?>

my favorite part about ArrayObjects is the ability to get an ArrayIterator for iterating over the values

<?php
  $iter = $arrayObj->getIterator();
  // i now have my iterator that i can iterate through in a couple different ways
  // 1) Java-esq
  while($iter->valid()){
    $curVal = $iter->current();
    // do something with the value
    // iterate to the next value
    $iter->next();
  }
  // 2) as an array in foreach
  foreach((array)$iter as $val){
    // do something with $val
  ...
  }
?>

This is just a quick intro to the ArrayObject, to see all of the features, see the SPL docs, or the in depth SPL doxygen pages

No Comments yet »

October 21st 2006

Switching Between PHP Objects and Arrays

Switching between Array and Object data structures is a snap with PHP’s object casting and the get_object_vars() function.

To switch from an Array to an Object, it’s a matter of a simple typecast

<?php
// start with an array of data
$personArray = array();
$personArray['name'] = "Brien";
$personArray['age'] = 29;
$personArray['gender'] = "male";
// convert to an object
$personObject = (object)$personArray;
// now all keys of $personArray are member variables of $personObject
// the data can now be accessed as member variables:
print( $personObject->age); // prints 29
?>

Converting the other way is just as easy using PHP’s get_object_vars() function

<?php
// start with a simple stdclass data structure
$personObject = new stdclass();
$personObject->name = "Brien";
$personObject->age = 29;
$personObject->gender = "male";
// convert to an Array of data
$personArray = get_object_vars($personObject);
// now all members of $personObject are keys in $personArray
// the data can now be accessed through Array indexes:
print( $personArray['age']); // prints 29
?>

No Comments yet »