PHP switch

Posted on Tuesday, August 31st, 2010 under , ,

Over the years, I’ve encountered a lot of strange things in PHP, but this one is off the scale:

$value = 'zero';
 
switch ($value) {
    case 0:
        echo 'value is zero';
        break;
    default:
        echo 'value is not zero';
        break;
}
echo PHP_EOL;

What do you think that the code above will print? Well…I’ll spare you the hassle and give you the answer:

% php test.php  
value is zero

This weird behavior originates in the fact that PHP uses the equality operator (==) instead of the identity (===) one when evaluating expressions inside a switch statement. It’s basically the same as:

if ('foo' == 0) {
    echo 'bar';
}

…which also yields unexpected results. I hate this type of casting!!!

JavaZone by Lady Java

Posted on Monday, August 16th, 2010 under , ,

Viral advertising in IT. I’m starting to like this…

Accessing a method defined in the current class’ “granpa”

Posted on Wednesday, August 4th, 2010 under ,

Problem: we have an hierarchy of 3 classes, each extending the one in front (grandfather, father, son). A method – let’s say foo() – is defined in the grandfather class and overridden with a new functionality in the father class.

Question: Is there a way in the son class to access the original method (with the grandfather code) in the son class?

Of course, the obvious solution is to try something like:

parent::parent::method();

But it won’t work. It will just yield an error like:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in …

After some struggling, I have found a way to get around and access a method from the grandparent class that was overridden in the parent and run its “original” code. It’s loosely based on the strange PHP scoping that I wrote about in this article. The approach goes something like this:

class Grandfather
{
    protected $_message = 'Luke, I am your grandfather';
 
    public function say()
    {
        echo $this->_message;
    }
}
 
class Father extends Grandfather
{
    protected $_message = 'Luke, I am your father';   
 
    public function say()
    {
        throw new Exception("I can't breath under this f**cking mask :(");
    }
}
 
class Son extends Father
{
    protected $_message = 'I have a very bad feeling about this';
 
    public function say()
    {
        Grandfather::say();
    }
}
 
$son = new Son();
$son->say();

Now PHP will bind the $this pointer in the body of the say() method – using the code defined in the grandfather. I guess that weird scoping is there for a reason.

PHP 5.3 certification beta-testers

Posted on Friday, July 9th, 2010 under

Zend is looking for beta-tester for its new PHP 5.3 certification programme. If you’re interested, all you have to do is simply take this survey and provide your contact details (so that they can find you).

Remove empty array elements with recursive lambda in PHP 5.3

Posted on Thursday, June 17th, 2010 under , , ,

How do you remove empty elements from a PHP array? The answer’s quite simple: array_filter(). Straight from manual and works like a charm:

$filtered = array_filter($raw);

Well, most of the time. It’s not recursive by default, so it only removes empty items on the first level of the array. If you have nested arrays and wish to remove all the empty items, regardless of their position in the matrix, array_filter() won’t work.

For example, let’s consider the following construct:

$raw = array(
    'firstname' => 'Foo',
    'lastname'  => 'Bar',
    'nickname' => '',
    'birthdate' => array( 
        'day'   => '',
        'month' => '',
        'year'  => '',
    ),
    'likes' => array(
        'cars'  => array('Subaru Impreza WRX STi', 'Mitsubishi Evo', 'Nissan GTR'),
        'bikes' => array(),
    ),
);

In this case, PHP’s built in array_filter() will miss the “birthdate” and “bikes” items. So, what now? Of course, you can create a function that will remove empty items recursively and pass it as a callback to PHP’s array_filter() function:

function removeEmptyItems($item)
{
    if (is_array($item)) {
        return array_filter($item, 'removeEmptyItems');
    }
 
    if (!empty($item)) {
        return true;    
    }
}
 
$filtered = array_filter($raw, 'removeEmptyItems');

But if you’re using a framework like Zend Framework that forbids using functions in the global scope and asks that all functions are wrapped in classes as static methods, things become more complicated and verbose. Yeah, yeah, I know, I’m a standards nazi :)

But if you’re using PHP 5.3, there’s a much simpler solution:

$callback = function($item) use (&$callback) {
    if (is_array($item)) {
        return array_filter($item, $callback);
    }
    if (!empty($item)) {
        return $item;
    }
};
 
$filtered = array_filter($raw, $callback);

Lambdas are sweet :)

Javascript based Flash Player

Posted on Wednesday, June 2nd, 2010 under ,

I stumbled upon this Slashdot article, about Smokescreen, a Flash player written entirely in Javascript and which can…are you ready for this…run on the iPhone/iPad/iPod Touch. In your face mr. Jobs!!!

Take a look at the demo, it’s very impressive.

I’m quite sure that by the end of the week Adobe will buy RevShock, the company that developed this player.

Constants for table names

Posted on Tuesday, June 1st, 2010 under

While working on a PHP project, I had the following idea: wouldn’t be better to use constants for table names? I mean, having a file, let’s say /application/config/tables.php, which would look something like:

define('TABLE_USERS', 'users');

And afterwards, use this value throughout the application:

…in the associated Zend_Db_Table_Abstract

class Users extends Zend_Db_Table_Abstract
{
    protected $_name = TABLE_USERS;
}

…in joins:

$this->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
 ->setIntegrityCheck(false)
 ->join(TABLE_USERS, sprintf('%s.id = %s.user_id', TABLE_USERS, $this->_name));

…in the forms:

$validator = new Zend_Validate_Db_NoRecordExists(
    array(
        'table' => TABLE_USERS,
        'field' => 'email',
    )
);

This makes much more sense to me, since writing a simple ‘users’ string can be interpreted as a “magic number“…well…string and it’s very hard to maintain, should one want to, let’s say, prefix some of the tables in the database with their module’s name.

For example, if there’s already an “users” table in system and, in a new module, there’s the need for another “users” table, it would be less confusing to prefix the old table it’s called “old_module_table” and the call the new one “new_module_table”. Encapsulating the table’s name into a constant makes this really easy. I think I’ll use this in my next project.

Serious privacy issues with photocopiers

Posted on Friday, May 28th, 2010 under , ,

…scary :)

Strange PHP scoping

Posted on Tuesday, May 11th, 2010 under , ,

I came to the conclusion that PHP is the programing language with the weirdest features. After the variable variables mess, that allows to you to name your variables stuff like !@#$%^&*()_+= and not be able to use them directly, I thought I saw everything. But no, yesterday I’ve bumped in another strange PHP feature. An even stranger feature.

Take a look at the code below:

class Example
{
    public function dynamicMethod($string)
    {
        // calls method baz() of the same class
        // class Example *does not have* a baz() method 
        $this->baz($string);
    }    
}
 
class Foo
{
    public function bar()
    {
        // a dynamic method called statically
        // no Example object is being instantiated
        Example::dynamicMethod('whatever');
    }
 
    public function baz($string)
    {
        echo 'Method baz() called with param "' . $string . '"' . PHP_EOL;
    }
}
 
$foo = new Foo();
$foo->bar();

What do you think the code will do? Yield an exception? A syntax error? Work? Well, strangely enough, it works:

Tudor-Barbus-MacBook% php blog-example.php
Method baz() called with param "whatever"

…and it seems that this feature is here to stay and be supported in the future, since I’m using the new PHP 5.3 version:

Tudor-Barbus-MacBook% php -v
PHP 5.3.1 (cli) (built: Feb 11 2010 02:32:22) 
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

I wonder how this can be useful to somebody.

Macbook – first impression

Posted on Monday, April 26th, 2010 under ,

Last week I got my hands on a Macbook for the first time and I must say I’m quite impress with it. I’m not an Apple fanboy that likes everything that has Apple’s logo on it. I bought once an iPod and that’s it. No iPhone, no iPad, no Apple stickers on my car. I don’t usually spend money on technology just for the sake of it. But the Macbook is different, I haven’t decided yet, but so far I think it’s almost worth the money :)

This is my opinion on it, compared with my other laptop, a HP running Ubuntu.

What I like

Let’s start with with the positive aspects:

  • Great look and feel, Apple’s designers pay attention to every single detail. And it shows.
  • Mac OS Snow Leopard, as it’s such a nice kitty
  • The touchpad interaction. Multitouch is the best technology ever. It feels so confortable.
  • Out of the box codecs and functionality. A lot of applications just work on Mac OS without the need for additional tweaking.
  • Better support from manufactures. If you’re using a Mac you’re posh and trendy and obviously willing to spend a lot of cash on technology, so companies try their best to provide you with working software, working drivers, working codecs and so on. It’s not like you’re one of those Linux freaks that compiles everything from scratch. :)

What I miss

There are some things I miss about my Ubuntu box:

  • The package manager. I miss it the most. It’s the best, just a sudo apt-get install and you’re there. Here things are more complicated, with downloads, accepting terms and conditions and even paying for the software you’re using :(
  • The directory structure. I know it’s a weird thing to say, but I’m used to /usr/bin and /home instead of /Applications and /Users.

What I don’t like

As nothing is perfect, here we go:

  • Cmd+tab cycles through applications, not windows. This one scores a perfect 10 on the “annoyance-meter”. Especially when you have application with multiple windows. You have to Cmd+tab to the desired application and then start Cmd+~ between windows.
  • The two fingers zoom on the touchpad. It’s fucking annoying, especially when you zoom my mistake. And you don’t even get a good degree of control. This isn’t all that annoying as it can be turned off.

Final verdict: as I said in the beginning, it’s almost worth the money. I’m not sure about this, but I think that my next laptop will be a Macbook Pro.