Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Larry Garfield:
Short and safe array iteration
Oct 26, 2017 @ 15:41:19

Larry Garfield has a new post to his site sharing a method for short and safe array iteration based on a "neat trick" he picked up reading a mailing list.

PHP's largely loose, dynamic typing has plenty of both pros and cons. One con in particular is that you don't always know for sure if a value you're trying to use has been set yet, or is non-null. PHP will dutifully whine at you if you try to use a null value, sometimes fatally. (Yet another reason to structure your code to avoid nulls, period.)

One place this comes up in particular is in foreach() loops, especially when working with nested array structures. (PHP lacks a struct type, but makes anonymous hash maps so easy that they get used as the uber data type, for better or worse.)

He gives an example of looping through a dataset with a foreach where the array index reference is used to reference the source array. While you could always wrap the loop in an if statement to check first, he has another interesting method to do the same thing. With the help of the null-coalesce operator (??) in PHP 7, you can essentially say: "if the array index referenced is null/does not exist, use an empty set". Check out the rest of the post for code examples putting this method to use.

tagged: array iteration nullcoalesce operator array null tutorial

Link: https://www.garfieldtech.com/blog/short-array-iteration

Stoimen Popov:
PHP: Don’t Call the Destructor Explicitly
Jun 27, 2016 @ 17:52:39

In a new post to his site Stoimen Popov makes the recommendation to not call the destructor explicitly in your code and provides some alternatives.

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++” says the documentation for destructors. [...] Well, as you can not call the constructor explicitly [...] so we should not call the destructor explicitly. The problem is that I’ve seen this many times, but it’s a pity that this won’t destroy the object and it is still a valid PHP code.

He talks about __destruct and it's role in PHP's set of "magic methods" and what they exist to do. He then gets into a few examples of what code could look like that uses a destructor and the difference between normal handling calling the destructor explicitly. The main differences is that calling it explicitly does not destroy the object, it's basically like calling any other method. He does include an interesting method for destroying the object - setting it to null - and notes that the destructor fires then too. He also points out a few interesting things about cloning objects and how object references work when setting nulls as in the previous example.

tagged: destructor explicit call object destroy null tutorial

Link: http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/

QaFoo.com:
Never Use null
May 03, 2016 @ 18:07:32

On the QaFoo.com blog they've made a recommendation in their latest post - they suggest that you never use null.

When doing code reviews together with our customers we see a pattern regularly which I consider problematic in multiple regards – the usage of null as a valid property or return value. We can do better than this.

Let's go into common use cases first and then discuss how we can improve the code to make it more resilient against errors and make it simpler to use. Most issues highlighted are especially problematic when others are using your source code. As long as you are the only user (which hopefully is not the case) those patterns might be fine.

They talk about some of the most common uses they see for using null in PHP applications including setters for class properties (injection). They point out that in PHP 7 a missing value on a property would result in a Fatal error and make the functionality harder to test overall. They suggest that all required dependencies be injected on object construction instead, making it easier to know the current state of the object on testing. They also talk some about using null as a return value, how it could make debugging difficult and a solution that could make more sense - throwing an exception instead.

tagged: never use null return value injection setter solution suggestion debugging

Link: https://qafoo.com/blog/083_never_use_null.html

Lorna Mitchell:
New in PHP 7: null coalesce operator
Sep 30, 2015 @ 15:51:52

Lorna Mitchell has a post to her site talking about a new addition to PHP in the upcoming major release of PHP 7 - the null coalesce operator. Despite its slightly confusing name, the operator is very handy for certain use cases with the ternary syntax.

Not the catchiest name for an operator, but PHP 7 brings in the rather handy null coalesce so I thought I'd share an example. In PHP 5, we already have a ternary operator, which tests a value, and then returns the second element if that returns true and the third if it doesn't. [...] There is also a shorthand for that which allows you to skip the second element if it's the same as the first one.

[...] In PHP 7 we additionally get the ?? operator which rather than indicating extreme confusion which is how I would usually use two question marks together instead allows us to chain together a string of values.

She includes an example of this new operator in use, chaining together a simple expression and showing the resulting output. It's a little confusing at first, but then if you remember it reads left to right it clears it up a bit.

tagged: null coalesce operator php7 feature example

Link: http://www.lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

Anthony Ferrara:
Security Issue: Combining Bcrypt With Other Hash Functions
Mar 13, 2015 @ 14:32:02

Anthony Ferrara has a new post today looking at a potential security issue in PHP applications when using bcrypt with encryption and other hashing functions. His findings have to do with some research he did on long passwords and denial of service attacks they might lead to.

The other day, I was directed at an interesting question on StackOverflow asking if password_verify() was safe against DoS attacks using extremely long passwords. Many hashing algorithms depend on the amount of data fed into them, which affects their runtime. This can lead to a DoS attack where an attacker can provide an exceedingly long password and tie up computer resources. It's a really good question to ask of Bcrypt (and password_hash). As you may know, Bcrypt is limited to 72 character passwords. So on the surface it looks like it shouldn't be vulnerable. But I chose to dig in further to be sure. What I found surprised me.

To find out exactly how things are processed he gets down into the C code behind the PHP functionality in the crypt function. He discovers something interesting about the way it determines the length of the input password. It loops over the key, taking one byte at a time but resetting when it comes across a null byte. While this method is safe in itself, he points out the real issue - using pre-hashing before the bcrypt password checking to, possibly, allow for longer passwords.

The problem is that this method could lead to those null bytes and cause issues with the password checking, especially if opting for the use of raw data. He includes a simple script to illustrate this problem, finding a few collisions for his made up key and "random looking" password. Thankfully, he includes a method for checking to ensure the hash doesn't contain a null byte. He points out that not all hashing combinations are at risk and suggests a few alternatives that can keep your application 100% safe.

The underlying problem is that combining cryptographic operators that weren't designed to be combined can be disastrous. Is it possible to do so safely? Yes. Is it a good idea to do it? No. This particular case is just one example where combining operations can be exceedingly dangerous.
tagged: bcrypt hash function combination issue crypt null byte

Link: http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html

Brandon Savage:
Always Return Something
Mar 12, 2013 @ 15:49:55

In this post to his site Brandon Savage talks about "always returning something" from your methods and functions back to the calling script. He also suggests that null is not an option.

A few weeks ago, there was a discussion on Twitter about whether or not a method should always return a value, or whether or not null was a valid value to return. The answer to this question is a resounding no, a null value should never be returned. [...] For example, you check that a file you opened exists, or that a resource performed correctly before using it. But if you receive a null response, how do you test for this The answer is you can’t

He notes that a "null" response is not only difficult to test but can lead to ambiguous handling as you're not sure where the error might be. He also includes a snippet of code showing how a null response could break a fluent interface if an instance of "$this" is not returned.

tagged: return valid null method function value

Link:

Michael Nitschinger:
A Journey on Avoiding Nulls in PHP
Feb 20, 2013 @ 18:17:39

Michael Nitschinger has written up a post looking at avoiding nulls in your applications in favor of a better kind of value handling - the introduction of "Optional" handling.

While every developer has kind of accepted their existence, they are suddenly there when we'd desperately need them to not show up. How often did you writeif($obj === null) in your PHP code? Can't there be a better, more elegant and fault-tolerant solution to the problem?

His solution is to create a PHP version of this "Optional" functionality (via an abstract class) that allows some evaluation of the returned value from method calls on the object. Methods like "isPresent", "getOrElse", "of" and "fromNullable" make it easier to work with null values instead of just the triple-equals checking. He includes not only the code for the classes you'll need to implement it but examples of it in use - an "Optional" abstract class and two child classes, "Present" and "Absent".

tagged: avoid null return value optional absent present evaluation tutorial

Link:

Stoimen Popov's Blog:
PHP: Don’t Call the Destructor Explicitly
Nov 16, 2011 @ 17:56:43

In this new post to his blog Stoimen Popov talks about calling the "destructor" method of an object and why doing it directly could lead to some issues - like not actually destroying the object before the script ends.

At the end of the script the interpreter frees the memory. Actually every object has a built-in destructor, just like it has built-in constructor. So even we don’t define it explicitly, the object has its destructor. Usually this destructor is executed at the end of the script, or whenever the object isn’t needed anymore. This can happen, for instance, at the end of a function body. Now if we call the destructor explicitly, which as I said I’ve seen many times, here’s what happen. As you can see calling the destructor explicitly doesn’t destroy the object. So the question is...how to destroy an object before the script stops?

He points out that one way to "destroy" an object is to null it out and remove the structure from memory. This is tricky, though, because a clone of the object will still exist in memory, just not the original.

tagged: destructor call directly null clone object

Link:

Dan Horrigan's Blog:
The Value of Null
Apr 19, 2011 @ 15:51:18

Dan Horrigan has a new post to his blog talking about the value of null - a quick summary about when and where null should be used. Null's a value too, after all...

Let me start off by saying this article is about PHP and PHP alone. Other languages handle this sort of thing differently (and better). In PHP many people (and a few frameworks) return FALSE from methods when the requested value does not exist. However, I am here to tell you that if you do this, you are doing it wrong. Plain and Simple.

In his opinion, "false" is definitely not the same thing as "null" because "null" is technically the absence of a value, not a "not true" value like "false" is. He illustrates with a simple use case of a class that has methods returning various values.

tagged: value null opinion false return

Link:

Jani Hartikainen's Blog:
What is a null object, and when are they useful?
Sep 14, 2009 @ 17:46:10

In this latest post to his blog Jani Hartikainen looks at creating "null objects" for your applications - a simple tool that lets you replace multiple evaluation checks with a simple object.

How many times have you written code, which checks if a value is null, and then displays something special because of that? Have you written the very same check in more than one place in your code? A null object is an elegant solution to this.

His example shows how to replace a standard User class to grab the user's name with an anonymous user that extends it to return the string "Anonymous User" instead. By creating an intermediate class like this, you can simple call a "getName" and know that there will be some sort of value as the result.

tagged: null object anonymous tutorial

Link:


Trending Topics: