Archive for the 'PHP' Category

Page 4 of 4

PHP Array syntax: array() vs []

Currently there is a funny discussion going on on the php.internals mailing list (Not the first time though). It’s a debate about the syntax of the array notation.
At the moment, when you want to create an array, you’d write:

$myArray = array(); // To initialize it
$myArray = array('value', 'foo', 'bar'); // Initialize, and fill it right away

What now gets proposed, is a shorter notation (some would say, more Javascript-like):

$myNewArray = [];
$myNewArray = ['value', 'foo', 'bar'];

I could probably say I’m in favor of adding the extra array syntax, as it shortens the notation for something as trivial as an array.

2 remarks I have about this, one in favour and one against it:

  • The array() notation as it currently is, is a bit ambiguous. It looks like a function but it’s not. The square brackets notation would be more consistent.
  • As Marcus told, somehow the ‘[]‘ array feels not so PHP like… This might be very subjective though.

PHP Constants, the lesser known ones

Often, when looking into people’s code, I find little code fragments that could be designed a bit more elegant. Sometimes the code needs refactoring or sometimes some design patterns needs to be applied.
This time though, I’d like to look at some PHP constants that are lesser known, but can make your code cleaner, less error-prone and more portable.

PHP_EOL:

Returns a line ending (EOL = End Of Line), depending on the operating system you run your code on.

$greeting = 'hello world';
$name = 'felix';
echo $greeting . PHP_EOL . $name;
 
#outputs:
hello world
felix

DIRECTORY_SEPARATOR:

Returns the directory separator for the current operating system. On Linux this is ‘/’, but for example on a mac, this is ‘:’. Using DIRECTORY_SEPARATOR increases portability of your code.

$path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'site.class.php';

PHP_INT_MAX:

Returns the upper bound value an integer can hold for the current operating system. Values will be different on 32-bit or 64-bit systems, so when dealing with large numbers on different hardware systems, take this in consideration.

PHP_OS:

Returns the operating system that PHP is installed on.

if (PHP_OS == 'Linux') {
echo 'yay, linux!';
} else {
echo 'ugh, windows..';
}

PHP_SAPI:

Returns the SAPI that you’re currently using. This is the same as the PHP function php_sapi_name(), but supposedly should work a bit faster, because there is no need for a function call. PHP_SAPI can be interesting if you want to write code that runs on either a website or independently on PHP Commandline (in which case, PHP_SAPI outputs CLI or CGI).

// Check if we're running commandline,
// in which case we can thread our application
if (substr(PHP_SAPI, 0, 3) == 'cli') {
$pid = pcntl_fork();
// ...
}

PHP Abstract podcast about Symfony

 PHPAbstract has a cool podcast up about the symfony framework. This is presented by Stefan Koopmanschap, web application developer at Ibuildings.nl.

His podcast is a brief introduction to symfony, what programming principles it uses, why it can be an advantage for you to deploy your project with symfony and more. A brief and interesting introduction talk to symfony.

The link to the podcast can be found here.

Installing symfony in a subdirectory of your documentroot

I recently needed to set up a Symfony install without a separate virtual host, so as a subdirectory of the (Apache) DocumentRoot directory (like: http://www.example.com/symfony/).

As you may know, symfony appreciates it when it has a reserved virtual host for itself, but also provides ways to just install it in a separate directory. The following steps need to be taken:

1. Change the apps/<yourapp>/config/settings.yml file and set relative_url_root


all:
  .setttings:
    relative_url_root: /subdir

2. Go to your front controller’s .htaccess file (usually in web/) and modify the RewriteBase directive


RewriteBase /subdir/

3. Optionally, if you want to omit the script name in production environment url’s, be sure to have enabled no_script_name = on in apps/<yourapp>/config/settings.yml


prod:
  .settings:
    no_script_name: on

4. If you took step 3, be sure to check if your apache installation has support for mod_rewrite enabled.

This way you can have nice url’s, like http://www.example/subdir/module/action
That’s it!

PHP Statistics for December 2007

The guys over at Nexen have their PHP statistics ready for december 2007. They give a pretty good impression on how much PHP is used on websites worldwide, and what the trends seem to be. Only one thing I found remarkable: only 27% of the servers running PHP are running PHP5! Good thing though: PHP 5.2.5 is gaining the most website increase in december, so we’re going the right way!

I’d say, with 19 days to go until PHP4 will reach end-of-life, three quarters of the PHP-using world better start making the switch :)

SPL_Types in php and strong typing

A strong typed programming language is a programming language where the datatypes of values have restrictions on them. The restrictions apply for what datatypes can be stored in variables, whether or not you can operate on those variables and more. To have an overview of a good definition of a strong typed language, see Wikipedia.

By default, PHP isn’t strongly typed. PHP variables and class properties can hold every datatype you wish for, and while doing operations on them, PHP internally uses implicit type casting to convert the one type to another. For example, you could do the following:

1
2
3
4
5
$stringVal = "5";
$intVal = 3;
echo $stringVal + $intVal;
 
# outputs 8

The first variable is initialized as a string, the second variable is an int. In any strong typed language, this would probably throw an error. PHP on the other hand, internally evaluates the operation and typecasts the string value to an int. What happens internally is the value is given to the C function convert_to_double(val);, which then makes the add operation possible and returning the int value 8.

This approach is flexible and definitely has it’s benefits, but sometimes you do want a strongly typed language. Luckily there is a PECL extension just doing that: SPL_Types. The working of this is best illustrated with an example:

1
2
3
4
5
6
7
$int = new SplInt(3);
$float = new SplBool(3.53);
try {
    $int = 'string';
} catch (UnexpectedValueException $e) {
    echo $e-&gt;getMessage();
}

As expected, this throws an Exception, because you tried to implicitly convert a integer to a string datatype. Similar SPL Classes exist for other datatypes too:

$int = new SplInt();
$float = new SplFloat();
$bool = new SplBool();
$enum = new SplEnum();

It’s available as a PECL extension, so the usual ‘pecl install SPL_Types‘ should do. It doesn’t make PHP a fully strong-typed language, but the SPL_Types extension isn’t meant to do so. It’s nice to have typing like this when you need it. To have a last example that might be of practical interest:

1
2
$input = $_GET['productCode']; # Unsafe way
$typeSafe = new SplInt($_GET['productCode']); # Type-safe way

Now, if anyone (maybe another developer) wants to change the input you receive from the $_GET['productCode'] key, if they try to do this:
$input = "myOwnProduct"; this will be perfectly valid, but not wanted. If you would do the same with our $typeSafe variable, an exception would be raised, telling you that the implicit typecast is not allowed, and thus improving security.

__callStatic in PHP 5.3

This is cool (and a feature I’ve been missing in past projects): being able to implement a __call method for static class methods.
Like this:

1
2
3
4
5
6
7
class Foo
{
	public static function __callStatic($method, $args) {
		echo "Method $method has been called!" .PHP_EOL;
		echo "With following arguments: " .implode(", ", $args) .PHP_EOL;
	}
}

So you can call

Foo::anyMethod('with', 'any', 'arguments');

and have a working static class method.

In this case, the method outputs

Method anyMethod has been called!
With following arguments: with, any, arguments

This is already implemented in the PHP 5.3 and PHP 6 development versions.
For more information on what __call (and the future __callStatic) magic methods do, see php.net Method overloading

PHP4 End of life, finally

Together with the last and final release of PHP 4.4.8, PHP4 is finally end of life. To quote the php.net news item:

The PHP development team would like to announce the immediate availability of PHP 4.4.8. It continues to improve the security and the stability of the 4.4 branch and all users are strongly encouraged to upgrade to it as soon as possible. This release wraps up all the outstanding patches for the PHP 4.4 series, and is therefore the last normal PHP 4.4 release. If necessary, releases to address security issues could be made until 2008-08-08.

I’ll post this release notice an effort to spread the word as much as possible: if you’re still developing projects in PHP4, you should seriously consider making the switch to PHP5. To have a quick look of what OOP goodies you can get in PHP5 (and thus make your programming life a lot easier), have a look here.

On the time of writing, there’s about 32 days left for PHP4 to be totally end-of-life. That’s 32 days to clear your php4 sins and start porting your applications to PHP5! To get to know more about that, see the GoPHP5 initiative. Or click the logo on the right menu. You won’t be sorry.

Zend Certification practising

I recently decided it was time to finally go for the Zend Certification Exam. Armed with the Zend 5 Certification Bundle (being the Study guide book, 10 test exams and a voucher to take the actual exam), I’m now ready to study and hopefully pass the certification.

One of the things I’m glad for are the small bits of code and theory in the study guide that still surprise me and that I’m still able to learn and improve myself on the knowledge of PHP and how it works internally.

Take, for example, the following code:

$a = array('zero', 'one', 'two');
foreach($a as &$v) {}
foreach($a as $v) {}
print_r($a);

You would expect for it to output array('zero', 'one', 'two'), but it does in fact output array('zero', 'one', 'one').

How is this possible? What happens in this case is after line 2, $v is a reference to $a[2]. On line 3, the foreach assigns a value to $v on each loop, which is still a reference to $a[2], so 3 loops take place:

$v ($a[2]) = $a[0], namely ‘zero’
$v ($a[2]) = $a[1], namely ‘one’
$v ($a[2]) = $a[2], itself!

As the last assignment tries to set it’s own value, it just uses the last value that was set to it, being ‘one’.

If the following concise explanation isn’t very clear to you, then you have a good reason to get the Certification guide and start studying! :)

To be continued, I’ll let you know when I’ll hopefully pass the exam :)