-
Yes, PHP is probably the most popular programming language on the server side for the web at the moment. And it’s probably going to be for a long while…
It’s probably the best!
That’s not really it, just read on…
Why is it so easy to learn?
First of all, it’s the syntax. It’s not the best syntax out there, the reason is actually that it’s the most popular! I knew most of the syntax before I even looked at a “hello world” example, why? I’ve studied C in school, and people coming from Java had the same feeling.
Let’s see a few programming languages that are using this syntax: Java, C#, JavaScript, Perl, Go, PHP and, of course, C and C++, and between them you have most of the market and platforms.
Unlike (most) other languages listed above, it’s a lot easier to get started! You don’t have to create a main function, a class or anything else to get started, you just get down to it!
The good part is that you can make it as complex as you want (or need) to, these days there are Java-like classes and interfaces, horizontal inheritance with traits, functional programming with closures and anonymous functions, generators and, if you really are a hipster, even goto.
But PHP doesn’t sound so bad…
Now, there is an important detail that must be mentioned, PHP didn’t become popular because of the features mentioned above, but the features came to it because of its popularity, even “goto”. I don’t know why somebody would add goto to a language more than 10 years after its creation but that’s none of my business, nor is it important for the subject at hand.
The language became really popular with versions 3 and 4. By the time a decent OOP model is introduced, it had already gained a lot of popularity! Now, especially more so since PHP 7 is looking a whole lot more like a decent programming language, but 10 years ago it wasn’t the same story.
But node.js will probably surpass it!
Right… remember Ruby? Python? And others…
If you think about PHP, it has a major advantage and disadvantage, is very much as stateless as it can be.
With PHP you feel like it doesn’t know anything about the world, you have to bootstrap everything all the time. The advantage is that if you have a memory leak, most of the time, it’s ok. The current user will finish and everything will get cleared and nobody will have to care. And PHP had a lot of memory leaks when it started to became very popular and nobody seemed to mind.
When people started making cron jobs and other long running processes, this becomes a big issue and the need for features like explicit garbage collection became a must. That was added with version 5.3, which was released in 2009.
Normally, continuous running should not be a disadvantage, so the moral of this story is that it’s not necessarily an advantage either.
Nobody is going to build the next Google on it, but how about some blogs? Or even better, some shopping carts?
It just doesn’t have what it takes for something like the Google search engine and that’s ok because it was just not designed for that.
Another example for “not necessarily the best will win” is that WordPress is the most popular blogging platform.
Even more, people are using WordPress for all kind of weird things, basically you can do anything with it! And you should not blame the people using it, it’s not like you look what’s in your microwave when you buy it, you just want to have a warm meal. People forcing the limit of WordPress are doing the same, they can do what they need, so there is no good reason not to.
Should I ever use it?
Let’s take a couple of positive examples: Yahoo! and Facebook.
Yahoo! has been using it for a very long time on some of their products and in combination with other programming languages.Facebook has been using it since the beginning because it is so easy to learn. They have been pushing the limit of the language in several occasions with: HipHop for PHP and more recently Hack, which was a very important motivational drive and a big influence for PHP 7.
Why all that trouble for a language? Because it’s just so easy to learn and use!
Usually, it’s a lot more important to release “now” then to have something “perfect” later, especially on the world wide web.
There is a very good reason why a language that is definitely not “the best”, but it is easy to learn is so popular online, while a programming language like C, which is way harder to learn, is more popular offline than online.
In other words, while definitely not being the best, PHP is most of the time just good enough.
-
IT is probably one of the most dynamic fields in the job market and people are a very important yet limited resource.
And yet people come and go quite often, and most of them are complaining about the lack of motivation.
This problem will end now with this simple guide for motivating programmers and not only them!
Programmers need challenging problems, they keep saying all the time that they need more challenges, don’t they?
Give your coder a true challenge! Make him get specifications from a client that doesn’t know what he wants, let him struggle, you could even try leaving him do this by himself, let him feel the adrenaline of a true challenge!
It must be noted that a programmer is nothing more than a repressed Project Manager, give him a chance to express!
However, you should not stop with that, because there is no greater challenge than to work on multiple assignments at the same time. A good idea for raising complexity is to offer him the chance to work on multiple projects in parallel. Give him the opportunity to have his mind busy with different things, diversity is always good, isn’t it?
A little secret for exploring diversity at its fullest is for him to have different roles on different projects, maybe have him alternate a project that requires management with one that requires maintenance. It’s a shame to not have enough diversity!
Is he writing a lot of code? You have to do something about it! When a programmer is focused working on something, keep in mind that he’s actually desperately crying for attention. You have to do something to break this vicious circle, it’s your duty as a manager to save him!
You have to find a way to interrupt him: try with a few meeting, they always help. If he is looking eager to get out of a meeting, it’s just a sign that he wants to get into the next one!
In time, you’ll see that the better a developer is at writing code, the more he’ll wish not to have time for it anymore. However, he’s not going to tell you this, or, even if he does, it’s because he really doesn’t know what he truly desires.
And eventually, if he likes to write code so much, maybe you should take it to the next level and get him to test it on his own. After all, if he wrote it, who would know better how to test it?
There is one more thing to mention in the context of a challenge. When a programmer is coming to an interview, he will always say “I want to learn new things”. How do you apply in real life this desire? Simple, you have to make him work on something that he doesn’t know anything about! This way you will present him with something that’s at the same time new and challenging. Is he a PHP programmer? Good for him, now give him a Java project! Is he a Java programmer? Nothing could be simpler, give him something to do in Objective-C! Maybe sometimes it will be hard to find new technologies the are completely unfamiliar to him, but a programmer’s happiness is not an easy thing to obtain!Try not to fall in the trap of offering salaries that are correlated with the position he applied for. Don’t worry, the salary is confidential, nobody talks about it. Especially not when he recommends a friend, he will definitely not inquire about the salary that was offered to said friend, if confidential. It would be a lack of professional ethics to try to find out, you really don’t have to worry about it.
And speaking of interviews, maybe you think that hiring processes should lead to meaningful results and qualified candidates. You couldn’t be more wrong, because what do you truly need? Like I’ve said before: Diversity! Not long ago I’ve read an article about some chinese companies hiring beautiful women to make the work environment more enjoyable and stimulating. You have to always find ways to integrate the new tendencies, and if the only open positions that you have are for technical jobs, you have to work with what you have. Maybe you think hiring based on looks can be problematic sometimes, especially when the jobs are technical. In this cases you have to realise that motivation has to be designed at a large scale. Yes, maybe some teams will require more time to adapt to this kind of new team members, however if that person has done something worth mentioning in any way, it means you’ve done a great job!
Let’s not forget about trainings and conferences. When did you last talk with a programmer saying that he doesn’t want to go to trainings or specialised conferences?
Motivation has to be maintained like any other desire. There are two components to it: wishing for something, and not least, not getting the something that is desired. If you wish for something it’s because you don’t have it yet, right?
If you didn’t already understand, the solution is simple: don’t let him have the something that he wants, so that he will be perpetually motivated to work hard in order to get it. He wants a training? Organise the training then make sure you are sending there the persons that are the least interested in it. He will see that he has a chance, but it wasn’t his turn right now.
Maybe this will sometimes be a challenge for management, but with a lot of carefulness it can be made possible! Keep the desire alive!
Another advice in regards to trainings: to keep the desire alive it is useful to send him to trainings in which he isn’t interested, but in which somebody else is interested. This way you will always have employees interested in trainings and having trainings, and also motivated!
When he is working he shouldn’t be able to see the usefulness of his work, it is very important. If he will see it, how can he be motivated still? It’s like climbing a mountain, no climber is motivated to go on if he knows how high he already is. You must be careful not to let him know where he is standing: keep those statistics and progress reports well hidden, because if he gets to have a feeling of ending, of target reached, of goal achieved, how would it be a true challenge then?
And don’t forget to not show him trust, he must build it for himself. You should provide him with a target and then keep it just a target. Indeed, a target achieved provokes pleasure and the satisfaction of a job well done, but is that what you want to show? Think about it, each time you congratulate him for his work will he be more motivated? Why try to stimulate him to improve when you can stimulate him to reach a target that he can’t. Don’t show him you trust him, let him struggle, let him feel the challenge.
In Romania we have a saying: “the known road is the shortest”. Regardless, some try to automate rudimentary tasks. Basically they are trying to eliminate the known road. Actually, if you prevent him from automating processes you are helping him remain busy, to have a busy mind, and a busy mind is an active mind!
And, secondly, with this approach you are helping him maintain his work place. Maybe he doesn’t realise it, but he will lose his purpose when he will remove exactly the tasks which, eventually, he knew so well, because he made them so many times… Programmer or not, he mustn’t be replaced by a robot!
Thirdly, it’s the satisfaction you get of walking the known road – don’t let him divert from it, because, it’s so well known that it should be finished quickly enough.
And never forget that you must teach him the importance of management. He must see that you can help him, that you are the key to his success and happiness. To show this it is very important to trust yourself. Try to organise a party and don’t invite him. Nothing says more “I could’ve been there” than not being there.
Another way is to organise a business trip in an exotic location. Don’t worry, it’s not important to actually have something to do there. While you’re there, don’t forget to have fun, it is very important for him to know that you’re enjoying yourself. When it gets though, you have to remember that you’re not doing this for you, you are doing your best to have fun for his and his imagination’s benefit!
Maybe some suggestions will not work for everybody, but you have to combine as many of them as possible to have a real success and keep your programmers truly motivated!
Don’t try to identify this utopian world, because any resemblance with the daily reality is purely coincidental.
-
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 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 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 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 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 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!
-
20 years ago, Rasmus Lerdorf announced a new tool called PHP.
My first encounter with PHP was in 2004, eager to make my HTML pages more dynamic. Somebody recommended PHP because it was very easy to use.
Because the installation seemed pretty complicated, I’ve used PHP Triad. In a few minutes I was ready to begin my experiments and I was fascinated by the instant feedback.
Back then, I was a student and my courses were based on Pascal and C/C++. I didn’t like Pascal because it was already outdated and C had a very complicated memory management system and instead of concentrating on the logical thinking I had to focus on allocating resources.
This new language, to me, had a syntax similar to C, but without the headache of resource management. Eliminating this impediment, I got to develop my logical thinking and even to become a better overall programmer, not only in PHP.
In that period, PHP wasn’t considered by many a “serious” programming language, more like one for beginners. At one of my first interviews, the employer told me on a nagging tone: “PHP is a toy, join us and you’ll learn real programming and something serious, like FoxPro!”. That was one of the moments that made me decide to become a PHP programmer.
11 years later, I can still say that PHP is the language closest to my heart, and I probably wouldn’t have had a career as a programmer without it.
What was your first interaction with PHP?
-
Something I didn’t approach in my last blog is collections. Hack comes with a variety of collections for organizing data.
Data structures represent a fundamental part of a programming language, because they will determine the information flow in the application.
PHP up to version 5 had a single type for data collections, called “array”. This data type can have three uses: array, hash table, or a combination of the two.
To facilitate the construction of new structures, a number of iteratori were introduced in PHP 5. Unfortunately, the resulting structures had the purpose of accessing objects in a similar fashion with arrays.
Not until PHP 5.3 data structures like SplStack and many others that are truly different were introduced.
However, structures like vectors and tuples were never natively introduced. They can be built, but it is neither simple, nor intuitive.
HHVM’s Hack comes with a different approach, a series of native collections that are ready to be used.
Collection types
The list of collections is:
- Vector – indexed list of items,
- Map – dictionary type hash table,
- Set – list of items that only stores unique values
- Pair – a particular vector case that only has two elements.
Vector, Map, and Set also have immutable (read-only) equivalents. These are: ImmVector, ImmMap and ImmSet. The purpose of these data types is to expose the information for reading purposes and not allow modifications. An immutable collection can be directly generated using the constructor, or using the methods: toImmVector, toImmMap and respectively toImmSet.
Even more, there are a series of abstract classes to help easily implement similar structures:
Vector
The advantage of a vector is that it will always have the keys in sequence and the order of the elements is not going to change. When it comes to arrays, there isn’t any simple way to check if it should behave as a hash table or as a vector. For vectors, unlike for hash tables, the key value is not relevant, only the sequence and the number of elements are important.
Let’s take an example:
1<?hh 2 3function listVector($vector) { 4 echo 'Listing array: ' . PHP_EOL; 5 for($i = 0; $i < count($vector); $i++) { 6 echo $i . ' - ' . $vector[$i] . PHP_EOL; 7 } 8} 9 10$array = array(1, 2, 3); 11 12listVector($array); 13 14// eliminating an element from the array 15unset($array[1]); 16 17listVector($array);
The result will be:
1Listing array: 20 - 1 31 - 2 42 - 3 5Listing array: 60 - 1 7 8Notice: Undefined index: 1 in ../vector.hh on line 6 91 -
The reason is very simple: count returns the real number of elements, but the index is not guaranteed sequential. When the second element of the array was removed, the number of elements was reduced by one, but the index with value 1 was no longer set and the last index is equal to the size of the array, so it will never be reached.
Let’s take the same example but using a vector:
1<?hh 2… 3$vector = Vector{1, 2, 3}; 4 5listVector($vector); 6 7// eliminating an element from the vector 8$vector->removeKey(1); 9 10listVector($vector);
Like we anticipated, the result is:
1Listing array: 20 - 1 31 - 2 42 - 3 5Listing array: 60 - 1 71 - 3
It is worth mentioning that “unset” can not be used, because it is not a key to be eliminated, but the element itself, and the next value in the vector will take its’ place.
Another important thing to mention is that when an index doesn’t exist, an exception of the type “OutOfBoundsException” will be thrown.
Some examples that will trigger the exception above:
1<?hh 2 3$vector = Vector{1,2,3,4}; 4 5// it will work because the key with value 1 exists 6$vector->set(1, 2); 7 8// it will not work because the key with value 4 doesn't exist yet 9$vector->set(4, 5); 10 11// it will not work for the same reason as above 12$vector[4] = 5; 13 14// for addition only method that don't provide the key work 15$vector[] = 5; 16 17// or 18array_push($vector, 5);
For accessing elements, the “OutOfBoundsException” problem remains the same. For instance, if the index 10 doesn’t exist:
1var_dump($vector[$unsetKey]);
Another more special case is when the element doesn’t exist, but the method “get” is used:
1var_dump($vector->get($unsetKey));
The example above will not generate an error, but the result will be “null” when the key doesn’t exist. I find this strange, because an element with the value null can exist in the vector, and the result will be the same.
To avoid the confusion between undefined elements and elements that are null, there is a special method to check if the key exists:
1var_dump($vector->containsKey($unsetKey));
Removing elements from the vector is done with:
1$vector->remove($key);
Or to remove the last element:
1$vector->pop();
Map
In a hash table, unlike a vector, the order of the elements is not very relevant, but the key-value association is very important. For this reason, a Map is also called a “dictionary”, because you can easily get from a key to a value, since they are “mapped”, hence the name “Map”.
The HHVM implementation will also retain the order in which the elements were introduced.
In PHP, the equivalent of a Map is an associative array.
Unlike Vector, Map needs a key that will permanently be bind with the element, even if new values are added or removed from the collection.
The functions array_push or array_shift will not work for Map, because a key is not sent and the key-value association would not be controlled:
1<?hh 2 3$map = Map{0 => 'a', 1 => 'b', 3 => 'c'}; 4 5array_push($map, 'd'); 6 7array_unshift($map, 'e'); 8 9var_dump($map);
Will generate the following result:
1Warning: Invalid operand type was used: array_push expects array(s) or collection(s) in ../map.hh on line 5 2 3Warning: array_unshift() expects parameter 1 to be an array, Vector, or Set in ../map.hh on line 7 4object(HH\Map)#1 (3) { 5 [0]=> 6 string(1) "a" 7 [1]=> 8 string(1) "b" 9 [3]=> 10 string(1) "c" 11}
As you can see, the elements were not added and each of the cases generated a Warning.
The actual insert can be done using:
1<?hh 2 3$map = Map{0 => 'a', 1 => 'b', 3 => 'c'}; 4 5// adding an element using the array syntax 6$map['new'] = 'd'; 7 8// adding an element using the method provided by the structure 9$map->set('newer', 'e'); 10 11var_dump($map);
The result will be:
1object(HH\Map)#1 (5) { 2 [0]=> 3 string(1) "a" 4 [1]=> 5 string(1) "b" 6 [3]=> 7 string(1) "c" 8 ["new"]=> 9 string(1) "d" 10 ["newer"]=> 11 string(1) "e" 12}
Unlike Vector, because the element is closely linked with the key, unset is a viable method for removing an element:
1unset($map[$key]);
The structure also has a method for removing the element with a particular key:
1$map->remove($key);
For this case, none of the options will generate an error, if the key is not set.
The “OutOfBoundsException” exception is also found here for keys that are not defined, and just like for Vectors, there is a method to test if the key exists:
1$map->contains($key);
Similarly to Vector, there is a method that will return true if the key exists and null if not:
1$map->get($key);
To make sure that a “OutOfBoundsException” will not be raised, a loop over a Map should not be done using “for” , but rather “foreach”.
Because the vector’s method “pop” does not use a key, it isn’t present in the Map structure.
Set
Set has the purpose of keeping the values unique. For this structure, the values are restricted to the scalar types: string and integer.
The interface for this structure is much simpler than Vector and Map, because the purpose is a lot more limited.
For Sets the key can not be accessed, but it is relevant in a special way.
Let’s take an example to illustrate this:
1<?hh 2$set = Set{'a', 'b', 'c'}; 3 4foreach($set as $key => $val) { 5 echo $key . ' - ' . $val . PHP_EOL; 6}
The result will be:
1a - a 2b - b 3c - c
The key and the value are identical, a clever way to keep unicity.
However, the process is transparent, fact that allows adding elements without a need for a key:
1<?hh 2 3$set = Set{'a', 'b', 'c'}; 4 5array_push($set, 'd'); 6 7array_unshift($set, 'e'); 8 9$set[] = 'f'; 10 11var_dump($set);
There will be a result similar to the one from vectors:
1object(HH\Set)#1 (6) { 2 string(1) "e" 3 string(1) "a" 4 string(1) "b" 5 string(1) "c" 6 string(1) "d" 7 string(1) "f" 8}
Even though new values can be added using the “[]” operator, they can’t be referenced using this operator:
1<?hh 2 3$set = Set{'a', 'b', 'c'}; 4 5echo $set['a'];
It will generate the following error:
1Fatal error: Uncaught exception 'RuntimeException' with message '[] operator not supported for accessing elements of Sets' in ../set.hh:5 2Stack trace: 3#0 {main}
For removing elements only the native method (remove) and methods that don’t require a key can be used:
1<?hh 2 3$set = Set{'a', 'b', 'c', 'd'}; 4 5array_pop($set); 6 7array_shift($set); 8 9$set->remove('b'); 10 11var_dump($set);
The result will be:
1object(HH\Set)#1 (1) { 2 string(1) "c" 3}
Unlike Vector and Map, the “remove” method will receive the value to be removed, not the key.
For Set there isn’t any access key for elements, therefore about all we can do is to check if an element exists, using “contains”:
1$set->contains($value);
The method will return a bool showing if the element exists or not.
Pair
A pair is a collection with two elements. It can’t have more or fewer. Just like in Vectors, the elements are indexed using a key that in this particular case can have only two values 0 and 1.
There aren’t a lot of things to be said about this data structure, because the elements can not be removed, added or replaced. This is the reason why it doesn’t have an immutable equvelent, because the structure itself is not flexible:
1<?hh 2 3$pair = Pair{'a', 'b'}; 4 5foreach($pair as $key => $val) { 6 echo $key . ' - ' . $val . PHP_EOL; 7}
The result will be:
10 - a 21 - b
A very simple structure for a very simple purpose.
Common ground
Almost all structures presented above have few common methods and behaviors. Almost all, because Set and especially Pair are more restrictive through their nature and lack some features which Vector and Map have.
Filter
It’s a filtering function that comes from functional programming. The purpose is to filter a data structure and to generate a new one of the same type. The exception is Pair, because of the number of elements restriction. The equivalent in PHP is array_filter.
Vector and Map have two methods: filter and filterWithKey. These methods take an argument of type “callable”, in other words a function:
1<?hh 2 3$vector = Vector{'a', 'b', 'c', 'd', 'e'}; 4 5// eliminate the element with value 'a' 6$result = $vector->filter($val ==> $val != 'a'); 7 8// eliminate every other element using the key 9$result2 = $vector->filterWithKey(($key, $val) ==> ($key % 2) == 0); 10 11var_dump($vector); 12var_dump($result); 13var_dump($result2);
The result will be:
1object(HH\Vector)#1 (5) { 2 [0]=> 3 string(1) "a" 4 [1]=> 5 string(1) "b" 6 [2]=> 7 string(1) "c" 8 [3]=> 9 string(1) "d" 10 [4]=> 11 string(1) "e" 12} 13object(HH\Vector)#3 (4) { 14 [0]=> 15 string(1) "b" 16 [1]=> 17 string(1) "c" 18 [2]=> 19 string(1) "d" 20 [3]=> 21 string(1) "e" 22} 23object(HH\Vector)#5 (3) { 24 [0]=> 25 string(1) "a" 26 [1]=> 27 string(1) "c" 28 [2]=> 29 string(1) "e" 30}
As you’ve noticed, the result of the “callable” function is treated as a bool and according to this the elements are added to the resulting structure.
Map has an identical behavior with Vector, the only difference is in the nature of the keys.
Something interesting is that a collection can also be immutable, because the operation doesn’t modify the original structure, but the it will also have the type of the original structure:
1<?hh 2 3$vector = Vector{'a', 'b', 'c'}; 4 5$vector = $vector->toImmVector(); 6 7// eliminate the element with value 'a' 8$result = $vector->filter($val ==> $val != 'a'); 9 10var_dump($vector); 11var_dump($result);
The result will be:
1object(HH\ImmVector)#2 (3) { 2 [0]=> 3 string(1) "a" 4 [1]=> 5 string(1) "b" 6 [2]=> 7 string(1) "c" 8} 9object(HH\ImmVector)#4 (2) { 10 [0]=> 11 string(1) "b" 12 [1]=> 13 string(1) "c" 14}
Pair also has the same functions as Vector and Map, but the behavior is not identical, because of the fact that Pair can only have 2 elements, no less, no more. For this reason, when a Pair is filtered, the result will be ImmVector, a similar structure with Pair but with a variable number of elements:
1<?hh 2 3$pair = Pair{'a', 'b'}; 4 5// eliminate the element with value 'a'
1$result = $pair->filter($val ==> $val != 'a'); var_dump($result);
The resulting structure will be:
1object(HH\ImmVector)#3 (1) { 2 [0]=> 3 string(1) "b" 4}
Set only has the “filter” method, because, as was demonstrated earlier, the keys are identical with the values. If it had had a method with keys, it would have worked the same.
Map
Another function coming from functional languages is “Map”. This aims to modify the values of a structure using a function, the resulting structure having the type of the source. In PHP, the equivalent is array_map.
Similarly with filter, Vector and Map have the common methods: “map” and “mapWithKey”. In this case also, they take a “callable” as an argument:
1<?hh 2 3$vector = Vector {'a', 'b', 'c'}; 4 5$result = $vector->map($val ==> $val . $val); 6 7$result2 = $vector->mapWithKey(($key, $val) ==> str_repeat($val, 1 + $key)); 8 9var_dump($vector); 10var_dump($result); 11var_dump($result2);
The result will be:
1object(HH\Vector)#1 (3) { 2 [0]=> 3 string(1) "a" 4 [1]=> 5 string(1) "b" 6 [2]=> 7 string(1) "c" 8} 9object(HH\Vector)#3 (3) { 10 [0]=> 11 string(2) "aa" 12 [1]=> 13 string(2) "bb" 14 [2]=> 15 string(2) "cc" 16} 17object(HH\Vector)#5 (3) { 18 [0]=> 19 string(1) "a" 20 [1]=> 21 string(2) "bb" 22 [2]=> 23 string(3) "ccc" 24}
The result of the “callable” function is the new value of the element in the structure.
Just like with “filter”, an immutable collection will result in a new immutable collection.
Also similar with “filter” is the fact that the “map” function applied to a Pair will result in an ImmVector:
1<?hh 2 3$pair = Pair{'a', 'b'}; 4 5$result = $pair->map($val ==> $val . $val); 6 7var_dump($result);
Will result in:
1object(HH\ImmVector)#3 (2) { 2 [0]=> 3 string(2) "aa" 4 [1]=> 5 string(2) "bb" 6}
Conversion
Some of the elements can be converted to different types:
from \ to Vector Map Set Pair Array Vector yes yes yes no yes Map yes yes yes no yes Set yes no yes no yes Pair yes yes yes no yes Array yes yes yes no yes There are several structural restrictions to the table above:
- Any structure that is getting converted to Set must only contain scalar values of type int and string:
1(Map{})->add(Pair {'a', new stdClass()}) 2 ->toSet();
Will generate the error:
1Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Only integer values and string values may be used with Sets' in …
- When a Map is converted to any other structure, except array, it will loose the keys in most cases.
The conversion from an array to other structures is done using:
1$vector = new Vector ($array);
Beside Pair, all structures above have a single parameter that implements Traversable for the constructor.
Conclusions
Hack brings a new perspective over the most popular data type in PHP. Facebook’s reason is a simple one, optimization. If you have a consistent behavior, that particular structure can be optimized. In PHP that’s not exactly possible, because of the fact that an array in PHP can be any type of collection.
From the data structure point of view, I find it interesting to have this kind of data types. In frameworks, there are usually structures that emulate the behavior of the collections introduced by Hack. For instance in an ORM, a collection of objects is usually represented as a vector, because the purpose is to iterate over its’ values. An object that represents the values of the fields from a table will be a Map like structure, because the value of the field is closely related to the field name.
I find it very interesting not only that now we have this structures, but also that we have the interfaces to implement new ones.
I hope Hack will influence PHP to bring purpose specific structures into the language.