Claudiu Persoiu

Blog-ul lui Claudiu Persoiu


Archive for the ‘php6’ tag

PHP6, just another story… (PHP6 and the books)

without comments

It’s finally over, the war has ended. PHP7 was released, and PHP6 will remain only a legend, a story of the version that never was.

After a while I don’t think anybody expected it to be released anymore. Afterall, it’s been almost 10 years, out of the entire lifetime of 20 years for PHP.

But how can such a highly anticipated version never show up?

Let’s begin from the start, when, almost 10 years ago, PHP was becoming a “serious” language. After the PHP5 version, the object module was finally having specific visibility for methods and properties, objects were no longer copied, but sent by reference. These changes triggered a multitude of object oriented frameworks, which were now also targeting the enterprise environment, not only small websites.

In all this context there was a problem, internationalisation.

This is how PHP6 appeared, it should have used natively Unicode, more specifically UTF-16. This way everything would have been processed in a unique and international format.

The project was started and maintained by Andrei Zmievski. Maybe today not many people know much about Andrei, but 10 years ago he was very popular for projects like Smarty and PHP-GTK.

After a few years the project got stuck, and then PHP5.3 appeared. Even though it was bringing important changes, it wasn’t a major version because there was still hope that one day there will be a PHP6.

There were however some people full of hope! And even more, they were ready to cash in on this bright hope!

Either authors or editors, they knew one thing when it came to books (especially technical ones) that they have two properties: a target audience and a period of relevance.

Let’s analyse the results.

PHP_6_and_MySQL_5_for_Dynamic_Web_Sites_Visual_QuickPro_GuidePHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide (3rd Edition) (Peachpit Press – 2008) – Larry Ullman

Larry wrote several books, including: “PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (2nd Edition)” and of course “PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide”.
Coincidentally, I had the opportunity to flick through all three books, but not in chronological order, I just randomly started with “PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (2nd Edition)”. What is interesting is the striking resemblance, basically a 6 was added to the title and the rest is almost the same.

In general, all books from Visual QuickPro Guide collection are targeting beginners, and from an edition to the next things don’t change too much, they are only adjusted.

Professional_PHP6_Wrox_Programmer_to_ProgrammerProfessional PHP6 (Wrox 2009) – Ed Lecky-Thompson, Steven D. Nowicki (Thomas Myer)

It’s interesting that in the cover image there are three authors, but on Amazon.com and on Wrox there are only two names, that’s why I wanted to single Thomas Myer out.

This makes me wonder if Thomas Myer purposely asked to be removed or were there other factors at play? It’s strange to have your name on the book but not in the author listing of the publisher’s website.

Not coincidentally there is also a “Professional PHP5” – Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove.

PHP_6_MySQL_Programming_for_the_Absolute_BeginnerPHP 6/MySQL Programming for the Absolute Beginner (Cengage Learning PTR – 2008) – Andrew B. Harris

It’s truly a strange book, there isn’t a PHP5 equivalent, and even more, on the writter’s website there isn’t any other PHP book.

Could there be a reason for that? In Larry Ullman’s case it’s just another covered subject, additional audiences targeted, but in this case it’s just strange, a single author, a single PHP book for a ghost version, published in 2008.

PHP_6_Fast_and_Easy_Web_DevelopmentPHP 6 Fast and Easy Web Development (Cengage Learning PTR – 2008) – Matt Telles, Julie C. Meloni

It wasn’t very difficult to also find: “PHP Fast & Easy Web Development” – Julie C. Meloni.

What is strange about this book is that Matt Telles doesn’t have any other PHP books, even though he wrote some for Python, C# and C++.

Something tells me he was brought in just to adjust the original book for the new context. I thought it was just a personal supposition, but upon searching on Google I found he is also Technical Reviewer for “PHP 6/MySQL Programming for the Absolute Beginner (Cengage Learning PTR)”, book that I covered above.

Beginning_PHP_6_Apache_MySQL_6_Web_DevelopmentBeginning PHP 6, Apache, MySQL 6 Web Development (Wrox – 2009) – Timothy Boronczyk, Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz

The original book was obviously: “Beginning PHP, Apache, MySQL Web Development” – Michael K. Glass, Yann Le Scouarnec, Elizabeth Naramore, Gary Mailer, Jeremy Stolz, Jason Gerner.

Michael K. Glass and Gary Mailer got out and in their place Timothy Boronczyk went in.

PHP was a very fashionable language in that period, and PHP6 was very awaited.

But how can something like this be? How can there be some many books from important publishers for a programming language that never existed? The answer is simple: greed.

There are two possible explanations: either the author tried to seize the market with a new version, or the publisher wanted to force it, in the hope of coining the market. Probably the hope was that when PHP6 was coming out, they would have already have the books ready for shipping.

This was another reason for not to rename PHP NG version into PHP6, it would have meant that a PHP version would have come out with a series of books already published, and what’s more, they were published for several years already.

I bet that when the vote between PHP6 and PHP7 was happening there were some very hopeful editors.

And now I wish you all, a pleasant reading!

Written by Claudiu Persoiu

22 February 2016 at 9:11 PM

Posted in PHP

Tagged with ,

There is life without PHP 6 – 2012 retrospective

with 3 comments

Another year has passed without native unicode support for PHP. Yes, PHP6 is not here yet, in case anybody was still asking…

But, the version that is now here is PHP 5.4. With this version only refinements were added, there weren’t changes as big as there were on PHP 5.3. In PHP 5.4, the big addition are “traits” and, my favorite, the new version for closure.

As the keywords for last year were Drupal and Magento, this year the keyword was only Magento.

A couple of months ago, more or less forced by the circumstances, I’ve taken the Magento Plus certification exam. For this certification, Optaros, my employer, had a major influence. We had been more or less made to take the exam and we also had to be part of a company level study group.

I haven’t been part of a study group since faculty, and I must admit that I’ve forgotten how useful it is. Colleagues with more Magento experience (unlike me who I’ve been working with Magento for a little more than an year), had helped a lot to clarify issues and to document them.

But more about this in another blog, that will follow shortly (I hope)…

Anyway, after studying Magento in so much detail, I must admit that I have a lot more respect for the platform. After you analyze the backend architecture, a different picture is emerging. The architecture is very interesting and quite flexible, which makes you overlook some of it’s shortcomings.

Now that a new year has begun, I wish I’m going to publish more, I think in the last period I haven’t been very “productive” when it comes to publishing, either text or code.

Also this year I want to take at least another certification exam. As the Magento certification was set only for this year, I still have a lot of options on my plate.

That’s about all for 2012 and plans for 2013.

I wish you an excellent 2013!

Written by Claudiu Persoiu

14 January 2013 at 9:54 AM

Posted in Diverse,PHP

Tagged with , ,

Another year has passed an PHP 6 remains a myth – 2011 in review

without comments

It became a tradition for me to begin my annual review on this subject.

PHP 6 is as close to be released as it was last year, or two years ago, which is without perspective. This year PHP 5.4 reached RC4 and a final version will probably be released soon, this means that work on PHP 6 will not be resumed soon. But more about PHP 5.4 with another occasion, is on my “TODO” list to see what got into RC4.

As the main keyword for me in PHP 5.3 were namespaces, Anonymous functions, closures and garbage collector, in PHP 5.4 it seems that those keywords are going to be traits, the new closures and scalar type hinting, next to many other new features.

When I’ve wrote my first annual review blog about PHP 6, I was mainly working on Romanian websites, hence my desire for a version that will natively support this language and any other without any changes. Back then I was mainly working directly with the language, without using a framework most of the time. But since then a lot of time has passed and many things have changed, now I’m using almost exclusively frameworks and other platforms that are taking me further away from the language, offering me a different architectural perspective.

After more then an year with NCH, I’ve decided that is time for a change. This is also a company from the states with a branch in Romania, and this time is Optaros. Although I wasn’t trying to change my work place, I’ve responded to an invitation to an interview, and long story short, I left. For a long time I’ve wanted to work again for external clients, after working at NCH where all the projects were internal, I’ve wanted a change.

Again the projects are even bigger, with other scalability issues. But I think that makes web development so interesting, the bigger the scalability issues, the bigger the project.

Last year the main keywords were Linux si Symfony framework. For this year that is just ending the main keywords probably were: Magento and Drupal.

After a short period of working with Magento, I can say that it seems incredible how a platform so big has so little documentation and a lot of the time so inconsistent. It is a very complex platform and a lot of things can be done with it, but when it comes to documentation, it seems like the usual approach is to just analyze the core. Coming from the Symfony world, where there are literary books for documentation, available for free, it seems incredible how little and disorganized is the Magento documentation. But this is also a subject for another blog. A think that the Optaros team played an important role in helping me understand how to approach the issues.

Another major event for me this year was the Yahoo! Open Hack Day, event that this year was also held in Romania. I don’t think I’ve ever seen so much enthusiasm and energy in a single place, in a single day. For me as a developer it was an unforgettable experience, one of those moments that remind me why I’ve chosen this profession.

Also this year I’ve passed my PHP 5.3 certification exam, at the beginning of the year. The exam wasn’t as difficult as I’ve expected, even though the tension remains the same. The fact that it wasn’t my first certification exam helped, it’s incredible how much you remember when you start the reading the documentation again. Last year I’ve decided that I have to take at least an certification exam every year, so I have to get started on preparing for the next one.

As a conclusion, 2011 was a good year, full of challenges and accomplishments, even though I haven’t checked a lot of entries on my last year’s resolution, I’ve done quite a few that were not on that list. But now is time for another new year’s resolution.

And now I wish you an 2012 full of achievements! Happy new year!

Written by Claudiu Persoiu

3 January 2012 at 4:45 PM

Posted in Diverse

Tagged with , , , ,

PHP 5.4 Alpha 1 is here!

without comments

Three days ago, that is on 28-06-2011 the PHP 5.4 alfa 1 version was announced on ww.php.net!

Basically in this release are the things that were made for PHP 6 and did not make it in PHP 5.3, next to some other new features.

Some of the most interesting new features are:

Traits

A new OOP feature. Basically for horizontal code reuse, that is inheriting of methods instead of extending classes.

trait Inharitable {
    public function test() {
        echo 'Class: ' . __CLASS__ . ' Method: ' . __METHOD__ . PHP_EOL;
    }
}

class A {
    use Inharitable;
}

class B {
    use Inharitable;
}

$a = new A();
$a->test(); //Class: Inharitable Method: Inharitable::test

$b = new B();
$b->test(); //Class: Inharitable Method: Inharitable::test

Traits in PHP 5.4 are the new namespaces of PHP 5.3, that is the most interesting feature in PHP 5.4.

Scalar type hinting

Up to PHP 5.3 there was type hinting only for classes, interfaces and arrays. With PHP 5.4 type hinting can be used for scalar data types like: int, string, float, book and resource.

function test(string $var) {
  echo $var;
}

$a = 'aa';
test($a);

Unfortunately on this alpha version on my computer I get: Catchable fatal error: Argument 1 passed to test() must be an instance of string, string given, called in .. on line 58 and defined in … on line 52

What can I say… it is still an alpha…

Closures

Yes, I know, there are closures in PHP 5.3 too, but there are not the same. In PHP 5.3 if you wanted a closure you had to use the keyword use and then specify the variables that the lambda functions will have access to.

In PHP 5.4 it’s beginning to look more like JavaScript, in a good way:

class closureTest {

    private $a;

    function test() {
        $this->a = 'object var';
        return function () {
            echo $this->a;
        };
    }
}

$a = new closureTest();
$b = $a->test();
$b(); // object var
unset($a);
$b(); // object var

Closure in the right way, with a lambda function the way it should be! Just like lambda functions existed even before PHP 5.3, but only after the new syntax they’ve become popular, now there was closures time.

This are some of the things that I find most interesting, but there are only a part of the new features that PHP 5.4 brings!

It’s likely that before the end of this year the final version will be ready.

I’m curious if with the final version of PHP 5.4 a new certification will come out, taking in consideration that the changes are not major.

Written by Claudiu Persoiu

1 July 2011 at 8:27 AM

Another year has passed and PHP 6 will not arrive

with 4 comments

Another year has passed and PHP 6 will not arrive.

Actually for the last couple of years I’ve been expecting PHP 6, and I believe this is more of a traditional blog for me to close the year.

PHP 6 will not come because the trunk was abandoned and rebuild from a 5.3.

Even if PHP 6 will not be out for a while now, PHP 5.3 is gaining popularity. Frameworks like Zend Framework and Symfony are each preparing in 2011 a 2.0 version that will need PHP 5.3+ to run. Even CodeIgniter, a framework that is was traditional PHP 4 compatible will need at least PHP 5.1.6 for version 2.0.

Even more, the official Zend certification for PHP is now ZCE 5.3, and it’s becoming very popular, even if it was released just few months back.

But a new year is ending and is time to check achievement from last year’s resolution and to write a new one.

Last year I’ve finished my masters, and with it I’ve finished way to many years to want to count of school. In fact this is the firs winter that I’m not in some form of school, maybe this is why I feel like I have so much free time :).

I’ve change my work place, and with it I was forced to use some things that were on my TODO list for quite some time:

  • Linux
  • Symfony Framework
  • Linux was a subject around I was gravitating inevitable for years, but never got to in to deep. It was always on my “todo” list, but never got the time or patience to really get into much detail with it, or didn’t have the continuity when I did it. When I got to my new work place I found my self in front of a Ubuntu computer, and I’ve started to panic a little.

    After few months I’ve made a new step, and for the first time in my life I went to a professional course. The course was organised by Info Academy. Paid from my own pocket and a little overlapped with my work hours. But I’ve reached the conclusion that I had to do it. Probably it does not sound like a big deal, but I usually study on my own, and it was quite weird for me. Now that is over I can say that it was a great investment and I recommend it (to all from Romania that can go to this centre).

    Sometime during that course I’ve realised that it was time to boot in linux from time to time even at home. The next step was to reconfigure the boot manager to boot directly to linux. Now that I’m almost exclusively use linux, I’ve reached the conclusion that is user friendly enough to be a real alternative to Windows.

    Symfony framework is another dusty entry on my “todo” list. Even if I’ve been playing around before with CodeIgniter and Zend Framework, I’ve never even got near to Symfony until last year. I’ve felt the fundamental difference of concept between ZF and Symfony. This was another reason to panic at my new work place, and after all: “all frameworks suck”.

    Is not a very easy to learn framework because of the concepts, but I thing it worth it. What I like most about this framework is the CRUD generating, that is very easy to do but is very powerful and flexible. Another thing is the use of YML files, which was taken from Ruby on Rails, is a way better alternative to the PHP’s native ini files.

    In the end, 2010 was a good year, with lot’s of achievements, even if I didn’t check everything on my last year’s resolution, I think I’ve checked enough.

    And now I wish you a great and full of achievements 2011! Happy new year!

    Written by Claudiu Persoiu

    31 December 2010 at 5:38 PM

    Posted in Diverse,PHP

    Tagged with , , , , ,

    Another year has passed and PHP 6 is still not here…

    without comments

    Another year has passed and PHP 6 is still not here…

    But that’s not exactly news, is the 4-th year when this long awaited version is not released. Not for nothing is called the most awaited version.

    But overall it was a good year for the community, even though we still don’t have native Unicode in a stable version now we have all other awaited features in PHP 5.3, which will probably need another few years to become used on a large scale.

    Even though everyone was expecting last year for Oracle to enter in full force on medium and small database market by purchasing Sun, enlarging it’s already well established  portfolio on the enterprise market. It seems that it was not to be, CE is still analyzing the deal.

    However MySQL is not what it used to be 5-6 years ago, when nobody dared to use it for enterprise products. This days MySQL is a product ready to be used in both small and large products that require a lot of scalability.

    But back to the year that just ended, it was a full year, even with this economic crises.

    Written by Claudiu Persoiu

    13 January 2010 at 8:30 AM

    Posted in Diverse,MySQL,PHP

    Tagged with , ,

    PHP and Unicode using UTF-8

    without comments

    One of the biggest issues with the web is encoding.

    In the old days the formerly base standard was  ISO 8859-1, where there ware 191 latin characters defined, and 1 char = 1B. For different languages, different encodings ware used, but from here many portability issues appeared, the possibility to cover a greater number of languages etc.

    The problem occurs when a project should be available in several languages, and the number of the languages is not controlled. A big project like WordPress for example should be available with any language.

    Unicode is a better alternative for ISO 8859-1, having more then 100.000 characters defined. In other words it has about every character of about any existing language.

    As I was saying for MySQL, UTF-8 characters have a variable length between 1 and 4B.

    Displaying the UTF-8 content in PHP pages

    For browser to interpret the page content as UTF-8, it should receive the right headers:

    <?php header("Content-type: text/html; charset=utf-8");?>

    Attention! The header should be the first thing that is send from the server! In other words it should be the first thing displayed on the page.

    The type of the document can be specified with the “Content-Type” meta tag. If there is a similar meta tag on the page it should be removed and replace with:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    The .htaccess file and string processing

    Add to the .htaccess file (for Apache servers) the following lines:

    # default charset used by PHP
    php_value default_charset utf-8
    # encoding for mbstring
    php_value mbstring.internal_encoding utf-8
    php_value mbstring.func_overload 7

    The first line sets the default charset for PHP, this setting can be made directly to php.ini.

    Second and third line sets the mbstring (multi byte string) functions.

    Using UTF-8, as I was saying earlier, 1 char != 1B, so errors may appear:

    $var = 'aşadar';
    
    echo strlen($var).PHP_EOL; // 7
    echo strtoupper($var).PHP_EOL; // AşADAR
    
    // using mbstring functions
    echo mb_strlen($var).PHP_EOL; // 6
    echo mb_strtoupper($var).PHP_EOL; // AŞADAR

    This is why we set the mbstring functions mode using the .htaccess file. Content entered through forms should be processed using mbstring functions, to avoid problems like in the earlier example.

    The available functions are in the manual.

    Coding old content

    There are many ways to encode ISO 8859-1 content to UTF-8. A couple of ways of doing that with PHP are:

    iconv() function which converts from a format to another specified format:

    echo iconv("ISO-8859-1", "UTF-8", "Test");

    utf8_encode() function which converts from ISO 8859-1 to UTF-8:

    echo utf8_encode("Test");

    What does the future bring?

    The long-expected PHP6 will have native support for Unicode, so all the above tricks will be unnecessary. At the moment of writing this blog PHP 6 is 70.70% done, and with a little luck it will be ready in less then an year.

    Written by Claudiu Persoiu

    11 August 2009 at 10:40 AM

    Posted in PHP

    Tagged with , , ,

    PHP 5.3 este aici!

    without comments

    Ieri a fost lansat oficial PHP 5.3! Aceasta versiune aduce cele mai multe schimbari de la versiune 5 pana acum, iar PHP 5.0 a fost lansat acum aproape 5 ani.

    Pe langa noile facilitati pe care le aduce versiunea (despre care am mai discutat), sper ca acum se va grabi si finalizarea lui PHP6, care in principiu o sa fie aproape PHP5.3+Unicode.

    De asemenea pe pagina PHP-GTK un anunt spune:

    Rumours of PHP-GTK’s death have been greatly exaggerated! The project is very much still alive, but we’re waiting for PHP 5.3 to come out, and also some work needs to be done on the Cairo extension before a new release can be made. This should be completed soon. This release will come with support for GTK+ 2.14 and 2.16, Cairo, and PHP 5.3.

    Din noutatile aduse, una dintre facilitatile care eu ma intreb in ce masura va prinde este PHAR. Aceasta permite crearea de “arhive” a fisierelor php, intr-un mod inspirat din Java unde se foloseste JAR. Accesarea arhivelor se face print-un stream (phar), deci teoretic se poate distribui o intreaga aplicatie PHP intr-un singur fisier, fara a fi nevoie de extensia PHAR sa fie instalata.

    Written by Claudiu Persoiu

    1 July 2009 at 10:32 AM

    Posted in PHP

    Tagged with , , ,

    PHP 5.3 final se apropie

    without comments

    Se pare ca PHP 5.3 aproape a fost lansat azi. Dar pana la urma lansarea a fost amanata pentru data de 30.06.

    Cum am mai spus si intr-un post anterior, PHP 5.3 este o versiunea destul de importanta aducand multe facilitati noi, care din pacate nu au putut fi lansate ca PHP 6, aceasta din urma avand (cand va ajunge sa fie lansata) suport pentru Unicode.

    Mai multe despre facilitatile aduse de PHP 5.3 in:  “PHP 5.3 ce aduce nou?“.

    Cred ca asta este un moment bun sa va verificati app-urile pentru compatibilitate.

    Written by Claudiu Persoiu

    25 June 2009 at 12:10 PM

    Posted in PHP

    Tagged with ,

    PHP 5.3 ce aduce nou?

    without comments

    Pana la versiunea mult asteptata 6, PHP 5.3 este deja la RC 2.

    PHP 5.3 vine cu multe lucruri noi, de fapt sunt atat de multe incat putea sa fie cu succes versiunea 6, dar de ce nu este PHP 6? Pentru ca toata lumea se asteapta ca versiunea 6 sa aiba suport Unicode, iar cand o comunitate de programatori asteapta de mai bine de 3 ani asta, nu poti pur si simplu sa le spui ca te-ai gandit sa lasi suportul pentru Unicode pentru versiunea 7.

    Namespaces

    Printre noutati se afla si namespaces, mi se pare o idee interesanta dar nu fantastica, initial acestea nu erau pe lista de prioritati pentru ca se considera ca problema lor se poate rezolva relativ simplu folosind prefixuri si clase.

    Un exemplu de namespace:

    <?php
    // clasa.php
    
    // definirea namespace-ului, in cazul asta trebuie sa fie prima instructiune din fisier
    namespace teste;
    
    // o clasa cu un conscturctor
    class clasaTest {
       function __construct() {
          echo "in constrcutor";
       }
    }
    
    // o functie
    function funcTest() {
       echo "in functie";
    }
    
    // o constanta
    const CONSTANTA = 'global';
    ?>

    Acelasi fisier se mai poate defini intr-un anumit namespace si in felul urmator:

    <?php
    // clasa.php
    
    // definirea namespace-ului
    namespace teste {
    
       // o clasa cu un conscturctor
       class clasaTest {
         function __construct() {
            echo "in constrcutor";
         }
       }
    
       // o functie
       function funcTest() {
          echo "in functie";
       }
    
       // o constanta
       const CONSTANTA = 'global';
    
    }
    ?>

    Fisierul in care fac testele:

    <?php
    
    // includem fisierul de mai sus
    require('clasa.php');
    
    $obj = new clasaTest(); // Fatal Error:clasa 'clasaTest' not found in ...
    
    $obj2 = new teste\clasaTest(); // afisaza "in constructor"
    
    // aparent suprascriem constanta
    const CONSTANTA = 'local';
    
    echo CONSTANTA; // afisaza "local"
    
    echo teste\CONSTANTA; // afisza "global"
    
    teste\funcTest(); // afisaza "in functie"
    
    ?>

    iar daca vrem sa nu mai folosim operatorul “\” si numele namespace-ului:

    <?php
    // trebuie sa fie prima insctructiune
    namespace teste;
    
    // includem fisierul de mai sus
    require('clasa.php');
    
    $obj = new clasaTest(); // afisaza "in constructor";
    
    // suprascriem constanta
    const CONSTANTA = 'local'; // Notice: Constant teste\CONSTANTA already defined in...
    
    echo CONSTANTA; // afisaza global
    
    ?>

    Si acestea sunt functiile de baza, folosindu-le pe acestea o sa ajute portabilitatea, si scalabilitatea. Acum numele de clase si functii nu mai trebuie sa fie unice, trebuie pur si simplu sa fie in namespace-uri diferite.

    Functile lambda si “closures”

    Cele mai interesante facilitati mi se par functile lambda si “closures”.

    Suna cunoscut? Poate pentru ca sunt foarte folosite in JavaScript:

    <script language="javascript">
    closure = function(text) {
       alert(text);
    }
    
    closure("hello");
    </script>

    Iar acum in php este posibil:

    <?php
    $closure = function ($text) {
       return $text;
    };
    
    echo $closure("hello");
    ?>

    Tot la functii lambda si “closures” a mai fost introdus si “use”, care permite folosirea unor variabile din exterior:

    <?php
    $x = 'Claudiu';
    $closure = function ($text) use ($x) {
       return $text.' '.$x;
    };
    
    echo $closure("hello"); // afisaza "hello Claudiu"
    ?>

    Iar daca in exemplul de mai sus vrem sa modificam variabilele care sunt parametri la “use” nu trebuie decat sa le trimitem prin referinta:

    <?php
    $x = 'Claudiu';
    $closure = function ($text) use (&$x) {
       $x = 'utilizator';
       return $text;
    };
    
    echo $closure("hello"); // afisaza "hello"
    
    echo $x; // afisaza "utilizator"
    ?>

    Iar ca sa luam un exemplu concret unde pot fi utile, sa zicem functia “usort“:

    <?php
    function cmp($a, $b)
    {
        if ($a == $b) return 0;
        return ($a < $b) ? -1 : 1;
    }
    
    $a = array(3, 2, 5, 6, 1);
    
    usort($a, "cmp");
    
    // este echivalent cu:
    
    $a = array(3, 2, 5, 6, 1);
    
    usort($a, function ($a, $b){
        if ($a == $b) return 0;
        return ($a < $b) ? -1 : 1;
    });
    ?>

    Dragut, nu? Cred ca asa se vede si mult mai clar ce se intampla in functie si la ce foloseste aceasta.

    De asemenea obiectele se pot comporta ca niste closures folosind noua “metoda magica” __invoke():

    <?php 
    
    class testCl {
       function __invoke() {
          return "metoda de closure";
       }
    }
    
    $obj = new testCl(); // instantiem clasa
    echo $obj(); // o apelam ca pe un closure si afisaza "metoda de closure"
    
    ?>

    NOWDOC

    NOWDOC este similar cu HEREDOC doar ca nu interpreteaza variabilele si caracterele speciale. Cu alte cuvinte HEREDOC era echivalentul ghilimelelor duble, NOWDOC este echivalentul ghilimelelor simple:

    <?php
    
    $var = "5";
    
    // ghilimele duble
    echo "Valoarea este: $var <br>"; // "Valoarea este 5"
    
    // ghilimele simple
    echo 'Valoarea este: $var <br>'; // "Valoarea este $var"
    
    // HEREDOC
    echo <<<HEREDOC
    Valoarea este: $var <br>
    HEREDOC;
    // "Valoarea este 5"
    
    // NOWDOC
    echo <<<'NOWDOC'
    Valoarea este: $var <br>
    NOWDOC;
    // "Valoarea este $var"
    
    ?>

    Operatorul “?”

    Acest operator a fost putin “inbunatatit”:

    <?php
    // inainte
    echo $_GET['ceva']?$_GET['ceva']:false;
    
    // acum
    echo $_GET['ceva']?:false;
    
    ?>

    Cu alte cuvinte acum conditia poate fi folosita ca valoare pentru adevarat.

    goto

    Sincer… nuprea vad de ce era nevoie de asa ceva, dar poate nu e chiar asa rau. Si un mic exemplu:

    <?php
    
    $x = 1;
    
    label1:
    echo "la label1 $x <br>";
    $x++;
    
    if($x>3) goto label2;
    goto label1;
    
    label2:
    echo "la label2";
    
    // va afisa:
    // la label1 1
    // la label1 2
    // la label1 3
    // la label2
    ?>

    Arata mai mult a Basic decat a PHP dar chiar functioneaza.

    Mai sunt si alte noutati, am incercat sa le enumar doar pe cele care mi se pare mie mai interesante.

    Din pacate toate aceste lucruri nu vor ajunge sa fie folosite cu adevarat pe scara larga decat poate peste 2-3 ani, sau chiar mai mult. Poate nu este PHP 6 dar eu cred ca toate schimbarile vor fi mai degraba asociate cu PHP 6 decat cu PHP 5, nu cred ca vrea nimeni sa riste o intreaga aplicatie care foloseste namespace-uri sau closures pentru ca nu este versiunea “noua” de PHP 5.

    Written by Claudiu Persoiu

    10 May 2009 at 5:42 PM

    Posted in PHP

    Tagged with , , , , ,