Creating an Instance of an Object without Calling Its Constructor in PHP

Today, I stumbled upon an article in a local PHP developers group. It was about creating an instance of an object without calling its constructor (as mentioned in post title).

At first, the idea made no sense to me. Because, constructor method is run every time an object is instantiated, this property is the whole point of writing a constructor. Out of curiosity, I started reading the article. As it turns out, it is really beneficial for testing and mocking purposes. The more interesting thing is the method used to achieve this is simply brilliant.

The trick which originally occurs in PHPUnit source code is as follows:

$object = unserialize(
    sprintf('O:%d:"%s":0:{}', strlen($className), $className)
);

As of PHP 5.4, there is a built-in method for this in ReflectionClass:

$reflection = new ReflectionClass($className);
$object = $reflection->newInstanceWithoutConstructor();

Storing MAC address in a MySQL database

Today, I encountered a problem: storing MAC address in a MySQL database. MAC addresses (something like “01:23:45:67:78:AB”) contain six hexadecimal (base 16) values. This means each hexadecimal field can store 256 (2 to the power of 8, in base 10) values. It’s 8 bits (= 1 byte) for each value.

6 field x 8 bit = 48 bit = 6 bytes

Thus, instead of storing the address as string, I prefer to store it as an integer. Because as a string (without colons “0123456789AB”), it can be stored in 12 bytes. Storing MAC address as integer allows us to store it using less space and also fast indexing.

In database, we can use unsigned BIGINT data type as it can store up to 8 bytes. While reading from database,

SELECT HEX(mac_addr) FROM `devices`;

While saving,

INSERT INTO `devices` (mac_addr) VALUES (x'0123456789AB');

If you prefer to make conversions in PHP,

function mac2int($mac) {
    return base_convert($mac, 16, 10);
}

function int2mac($int) {
    return base_convert($int, 10, 16);
}

You can use this function to make the address human readable

function int2macaddress($int) {
    $hex = base_convert($int, 10, 16);
    while (strlen($hex) < 12)
        $hex = '0'.$hex;
    return strtoupper(implode(':', str_split($hex,2)));
}