New Features in PHP 5.6
sitepoint.com
sitepoint.com
Since PHP 5.3, PHP has gotten some really nice features, they've definitely been doing a pretty good job over the past few years.
It's going to take a ferocious amount of work to shed its reputation as a web-only scripting language.
What? It is web-only. That's the entire point behind it. It's not a reputation, it's the goal of the project.
Its absolutely awesome barring having to work with the websocket framing protocol with ordinal casts, etc. PHP has an odd flavor of hex/ binary arithmetic. You pretty much just pull characters out of a string byte by byte and use bit shifting/ ANDing to get a message decoded.
And the best part! No need for anything like APC for the cli; it's useless as the daemon doesn't work like a standard PHP lifecycle in apache.
Given an arbitrary back-end written in Python, Ruby, Go, Perl, Java, Scala or PHP I would expect, nine times out of ten, the bad apple to be PHP.
Anyone who knows how to program PHP properly, and by that I mean using all of the modern conventions, would be far more productive in something like Java or Python where they didn't have twenty years of appallingly bad design decisions influenced by its role as a web scripting language weighing down their code.
Yes, because Java doesn't have it's own twenty years of bad decisions...
Why would anyone write non-web code in PHP? It's completely out of its element.
If your selling point is "not having to learn" you're not being very fair to developers that use PHP. If you can't learn, you've got a problem. New technology comes up all the time, and if you can't adapt, you'll get left behind.
Would you recommend a PHP to JavaScript converter so you can do PHP in the browser and avoid all that painful "learning"?
What about "bash beyond the shell"? It's possible. Would you want to write an application in bash? Please, do not.
Everything that made PHP popular and versatile is now a massive liability. Perl went through the same cycle from saviour to relic and that community has been struggling to try and reinvent itself (Perl 6) in a manner that's in keeping with today's concerns.
The level of change you'd have to introduce in PHP to make it current is so staggering you may as well write a whole new language. Even the relatively modest changes made to modernize Python have caused an enormous rift.
Like their OOP and Namespaces - Sure, cool that PHP has those but compared to other languages like Ruby, C#, Java, etc.. PHP implements these futures horribly.
If you're looking for mis-features, you need better examples than these.
PHP is painful to work with for a lot of reasons. It's also very easy to work with for a lot of reasons, but in my opinion, a lot of those -- despite being considered by some to be strengths of the language -- are used, and in many cases intended, to be shortcuts to functionality a more robust language would embrace explicitly.
PHP suffers from many, many failures of design. It suffers further, and worse, from an ongoing and intentional failure to address almost all of these failures. It's Frankenstein's language. If it were sentient, it would rebel and run off into some cold and inhospitable place.
A fast pace is velocity. They have that. What they don't have is a good direction, and without a good direction, a long vector is at best a roll of the dice.
At the end of the day, if you keep it simple you can go far without ever needing to do much maintenance and scaling. Most failure to scale I've seen come from bloated code base and code written by people who are not PHP developers.
That said, the new ...$params is 100% better.
They had a proposal a while ago to add getter and setter function support, which would be cool and would've allowed it (with some function overhead), but is probably a bit OTT for PHP.
readonly properties would allow you to make truly solid classes. You'd be able to lock them down from outside interference.
Methods could trust that property values hadn't been tampered with from outside, while still providing a way for outside code to read those values extremely quickly, without function overhead.
I think it's an awesome idea, especially since the getter/setter proposal failed. It's very PHPy, and it strikes a nice middle ground between fully public properties and private ones.
External code really shouldn't be able to mess with my class's internal properties anyway, it violates separation of concerns.
It's so easy to do that a readonly keyword seems unnecessary.
class whatever{
private $Properties=array();
function __set($key,$val){
try{
if(!isset($this->Properties[$key])){
$this->Properties[$key]=$val;
}
}catch(Exception $e){
//...
}
}
function __get($key){
try{
if(isset($this->Properties[$key])){
return $this->Properties[$key];
}
}catch(Exception $e){
//...
}
}
}The catch will never be called, and you should never use isset() because it will return false if the value exists but is null.
whatever->param = null;
whatever->param = 123;
Both lines will execute here. function __set($k, $v){
if (array_key_exists($k, $this->Properties)){
throw new ReadOnlyException();
}else{
$this->Properties[$k] = $v;
}
}The correct approach is slow and steady improvements. I suspect standard library improvements will come not by renaming existing functions but by adding new API.
Then you can do extensions [even changing central functionality] in a sane way, with backward compatibility. (A language implementation need to implement deprecated features for older versions, of course.)
I agree with your point re APIs.
set_minimum_version('My/New/Component', '5.7.8');
This could be called in the component itself or maybe by a composer autoloader. Then PHP components that expect different version could live together.The big problem, as you mentioned, is that the interpreter would have to maintain all the deprecated features and behavior for older versions and that would make development and maintenance of PHP much more complicated.
Oh, good luck trying to match all unicode punctuation with Python/Javascript. With php it is as simple as preg_match('/\pP/u'
I deal with a lot of UTF-8 issues, and while php is super ugly, there are pretty good solutions in cases where it requires ugly hacks in other languages.
Native UTF is such an important thing... I know it's tough to implement, but come on guys!
I think there's something that needs to be fixed at a core level, maybe with PHP 6, that just guts how the language deals with multibyte. Even if it means making it backwards incompatible. I'd probably take the opportunity to drop the mb_ functions, namespace the entire language, and make it multibyte by default. Needs doing eventually!
If people have encoding issues in PHP it usually just means that they didn't manage to set up their database properly (you know, finding which one of the 10 encoding options in MySQL is the right one ;)
From my personal experience I've had a lot more issues with encoding in Python than I had in PHP - exactly because PHP ignores encoding and lets me deal with it.
$binString = "hello";
$unicodeString = u"Hello";
strlen($binString); // 5
strlen($unicodeString); // Error
And then developers can slowly start making functions and methods more unicode aware as necessary. Or make an entirely new string API. Then just have functions to take binary strings and convert them to unicode strings (providing an encoding) and unicode strings to binary strings (also providing an encoding).This would be way safer and simpler than PHP6 or Python 3.
- strlen can't be used for length checks if you care about length in characters, a problem compounded when you use a real database where field lengths are defined in characters instead of bytes
- the only way to iterate char by char instead of byte per byte is to use mb_substr, as there is no trick to make $str[$i] do anything but return bytes.
- the string and array API's have inverse ordering of their parameters, which means that after a decade of writing PHP I still can't remember which is which without looking it up
- Typing mb_ in front of everything is ugly enough, but it also makes autocompletion tricky, especially since the strings don't have methods. (e.g. $str->pos())
- Speaking of which, since the strings don't have methods, they stick out like a sore thumb in OO code. String and array handling code invariably ends up ugly unless you write everything procedural style (and then you have other issues).
- Sort() cannot be made to sort unicode on windows, regardless of which parameters you give it. In fact, the only way to sort unicode on windows is by using the Collator from the intl extension. Part of that is microsoft's fault by not supporting UTF-8 in the windows API's at all, but PHP isn't helping.
- If you don't care about windows, the proper way to sort text is first calling setlocale(LC_COLLATE, "en_US.UTF8") and then passing the SORT_LOCALE_STRING argument as second parameter to every call to sort(). Ugly, ugly, ugly.
- natsort(), aka "natural sort" cannot be used to sort text like a human would expect, in any context. It always produces invalid results, even for ANSI codepages. (e.g. try to sort resume, rope and résumé)
- The use of utf8_decode and utf8_encode is actively harmful in almost all circumstancces. There is never a good reason to use them, since the very rare case where you need them iconv or mb_convert_encoding are better suited. Yet, the PHP documentation doesn't tell you this, causing lots of people to be led astray (as I once was).
- Oh yeah, and there are no less than three API's for unicode string handling, the mb_ functions, the iconv_ functions and the grapheme_ functions. What's the difference? I don't know, and I really can't be bothered to read PHP's source to find out.
- htmlentities() always requires the parameters ENT_QUOTES, "UTF-8" to do its job securely (well, almost, as it doesn't encode forward slash which OWASP recommends). Unless you use a wrapper, your code is yet again uglified.
- The secure way to JSON-encode text is, and I kid you not, json_encode($data, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP). Try typing that three times in a row, I dare you.
- And finally, mysql is by far the worst database for unicode handling, because it cannot sort unicode text according to the standard, at all, no matter what you do. That's not PHP's fault ofcourse, but since I'm bitching... :)
We send back a json_encoded array containing a property "html" with html markup to be injected back into a contenteditable div. Originally I had a ton of problems if there happened to be the invisible unicode character in there (php's str functions could not find/replace this character no matter what I tried). However, this is the first I've seen those flags the GP mentioned.
function AsJSON($arr, $cruft=null){
//convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127).
//So such characters are being "hidden" from normal json_encoding
array_walk_recursive($arr, function (&$item, $key) {
if (is_string($item)){
$item = mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8');
}
});
$JSON = mb_decode_numericentity(
json_encode($arr, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP),
array (0x80, 0xffff, 0, 0xffff),
'UTF-8'
);
if(json_last_error() === JSON_ERROR_NONE){
return $cruft.$JSON;
}
}
You might also consider looking at the ctype_* functions if you haven't.You can identify them by pack("CCC",0xef,0xbb,0xbf), encoding to ""
But then again, my name gives me special powers.
Modifying the content by default would be completely counter-intuitive, specially with a function that is used mostly in API and thus being encoded / decoded in different places and languages.
IMO content filtering is specific to the view where you output it, and should be done there. Any hazardous content should always go through a sanitize function when you echo it in the middle of HTML.
80% of your points can be answered by wrappers/helpers. How often do PHP developers have to walk through a user-generated string of multibyte cacarcters? Ok, didn't think so. And when you do you have all the required tools. 99% of string handling is simple copy, and the byte apporach is great at that.
A few points that stand out, and give an amusing idea of how you implement stuff:
"Unless you use a wrapper"
"What's the difference? I don't know, and I really can't be bothered to read"
"Try typing that three times in a row, I dare you"
"Oh yeah, and there are no less than three API"
"a real database where field lengths are defined in characters"
"makes autocompletion tricky" on native function...
PS:- natsort() is intended for numbers
- ENT_QUOTES isn't required unless you use single quotes to encapsulate your outputs
- ugly code = using different function names.. ok
- PHP isn't helping Microsoft.. ok
- utf8_decode is a shortcut for iconv() using the 2 most common encodings, just FYI
Edit: formatting
That being said, when there is a problem, there actually is a solution. PCRE actually works. Javascript, for instance, has no collation support at all as far as I can tell.
Personally, most of the problems with UTF-8 are mixed content issues.
The best fix is not the Python route, but rather just deprecating a bunch of stuff such as utf8_encode/decode. Throw a warning when any database connection is not utf8. Throw a warning when the OS is not setup to return UTF-8. It is more important that people run php in a end-to-end utf-8 environment, than changing the internals. Once people have a good environment, they will stop talking about strlen/strpos which are really not much of a problem. Maybe they should be renamed bytelen/bytepos, but php has too many of that type of problem to count.
99% of the UTF-8 problems don't exist if everything is UTF-8. Counting unicode code points vs bytes is not the real problem. The real problem is bullshit like 'SET NAMES utf8' / setlocale('LC_ALL','en_US.utf-8')
BTW, what language do you think gets this stuff right? Go looks promising, but it is brand new. I have problems with pretty much every language I know well: javascript/python/Objective-C/PHP
So how about them using the -> operator? Most languages that use . for class method access also reuse it for namespacing.