Is the PHP Intl extension thread safe?

对着背影说爱祢 提交于 2019-12-05 14:12:03
Decent Dabbler

Ok, I was curious about this myself as well, so I devised a test.

First I tested setlocale() with these two files:

<?php
# locale1.php
error_reporting( E_ALL | E_STRICT );

date_default_timezone_set( 'Europe/Amsterdam' );
setlocale( LC_ALL, 'dutch_nld' ); // awkward Windows locale string

sleep( 10 ); // let's sleep for a bit here

echo strftime( '%A, %B %d, %Y %X %Z', time() );

and

<?php
# locale2.php
error_reporting( E_ALL | E_STRICT );

date_default_timezone_set( 'America/Los_Angeles' );
setlocale( LC_ALL, 'english_usa' ); // awkward Windows locale string

echo strftime( '%A, %B %d, %Y %X %Z', time() );

Then I executed them in two seperate tabs. First locale1.php, that sleeps for 10 seconds after setting the locale, giving us time to execute locale2.php in the meanwhile.

To my surprise locale2.php isn't even allowed to change the locale correctly. It appears sleep( 10 ) in locale1.php hijacks the Apache/PHP process in such a way that it doesn't allow locale2.php to alter the locale in the meanwhile. It does however echo the date in the meanwhile of course, just not localized as you'd expect.

Edit: sorry, scrap that. It appears locale2.php does change the locale and locale1.php then prints the English date in stead of Dutch after sleeping. So that does appear to be in accordance with what is expected behavior from setlocale(). /Edit

Then, I tested IntlDateFormatter with these two files:

<?php
# locale1.php
error_reporting( E_ALL | E_STRICT );

$dateFormatter = new IntlDateFormatter(
    'nl_NL',
     IntlDateFormatter::FULL,
     IntlDateFormatter::FULL,
     'Europe/Amsterdam'
);

sleep( 10 ); // let's sleep for a bit here

echo $dateFormatter->format( time() );

and

<?php
# locale2.php
error_reporting( E_ALL | E_STRICT );

$dateFormatter = new IntlDateFormatter(
    'en_US',
     IntlDateFormatter::FULL,
     IntlDateFormatter::FULL,
     'America/Los_Angeles'
);

echo $dateFormatter->format( time() );

and then executed them again in two separate tabs, the same way as with the first set of files. This does give the expected results: while locale1.php is sleeping locale2.php nicely prints a date in American-English according to American rules, after which locale1.php nicely prints a date in Dutch according to Dutch rules.

So, concluding, it appears Intl is safe from that setlocale problem.

But also mind Hyunmin Kim's answer of course. I couldn't comment on that, due to lack of experience with using Intl. I only recently discovered Intl.

The Intl extension is safe and very useful if you're working not working inside a framework.

For example, if you're using Symfony2, your programs will most likely crash when using Forms and Validators.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!