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

Tomas Votruba:
The Rocket Science Behind Migration of Docblock Types to PHP Typehints
Dec 13, 2018 @ 17:56:53

In a post to his site Tomas Votruba takes a look at the "rocket science" behind the migration of DocBlocks to typehints in your PHP application.

What if you could add scalar typehints int, bool, string, null to all parameter type and return type by running a CLI command? But also all classes, parent, self and $this?

Do you think it's an easy task to move @param int $number to (int $number)?

He talks about some of the current tools that handle the conversion of type-hints to type checks, but points out that some of them break the code (as they don't have the right context). He shares the results of some of his own research using these tools and issues that can come up with code changes. He also includes issues that could come up with the use of self/parent and namespacing. The post ends with some instructions on using the rector/rector package to handle this refactoring in a bit better way (including the configuration required).

tagged: migrate dockblock type typehint tutorial rector package

Link: https://www.tomasvotruba.cz/blog/2018/12/10/rocket-science-behind-migration-of-docblock-types-to-php-typehints/

Larry Garfield:
PHP: Never type hint on arrays
Jul 30, 2018 @ 17:05:48

In a new post Larry Garfield makes an interesting suggestion related to the use of arrays in PHP. He suggests that you should never type hint arrays in your method definitions.

Let's be controversial: In modern PHP, you should never type-hint an array. Before you start throwing tomatoes, hear me out.

PHP allows you to specify the type of a function/method parameter or return value. These return values can be any legal PHP type. [...] PHP has a data type that it calls array, although it's not really an array as any other language would define it. [...] And you should almost never use array as a type hint. Why? Because there's always a better, more generic option.

He starts off talking about the use case where arrays are used as a "single complex value" and how,. more often than not, a class is actually a better option. He then covers the other main use of arrays: as an ordered sequence of values. To replace this he recommends a more structured collection that can apply some logic to its contents. With these other options out of the way, he then talks about what arrays are actually useful for and some other potential typehints to allow arrays and other potential inputs. He ends the post talking about array operations included in PHP and how, with a minimal amount of effort, they could be reproduced with simple methods for use on actual collection instances instead.

tagged: typehint array options class collection opinion

Link: https://steemit.com/php/@crell/php-never-type-hint-on-arrays

Matthieu Cneude:
PHP type hinting: what you shouldn't do
Jan 04, 2018 @ 18:12:06

Matthieu Cneude has written up a post for his site that shares some of his thoughts around what you shouldn't do with type hints in your code.

When PHP 7 came up with strong types, I saw the light. I had the hope not to see anymore bugs and inconsistencies due to weak typing in PHP. I remember reading some code and having no idea what could be the type of the variables I had in front of me.

[...] Strict types are big help as well as return type hint. You know what is the data you're manipulating. You don't have to guess anymore. However, PHP 7 wasn't the end of my typing struggle. You can still add a lot of ambiguity even if apparently PHP 7 tried to fix the problem. You still need to follow a couple of rules to keep your code consistently typed.

He then goes through some examples of weird results with some return type hints and unexpected results. He then moves on to strict type mode and how it can help resolve some of the oddities he discovered with just return type hints. The article spends the remainder of the time talking about the nullable type hint and some of the other "fun" surprises that can come from its use too.

tagged: typehint opinion oddity returntypehint strict type tutorial

Link: http://web-techno.net/typing-with-php-7-what-you-shouldnt-do/

David Négrier:
Type-Hint All The Things
Jul 05, 2017 @ 17:52:53

In this new post to his site David Négrier talks about "type hinting all the things" in response to a recent controversy around "clean code" and "visual debt" in PHP code.

Recently, a video about "visual debt" as sparked a lot of controversy in the PHP world. In this article, I'll present the best practices we are using at TheCodingMachine, and a brand new tool we use to enforce those best practices.

If you haven’t seen the video yet, you can have a look at it on Laracast. At some point, the video advocates to remove the type-hints because they are not needed by the program and are "visually polluting" the code.

He then breaks down his look at type hinting and the benefits they can provide into a few sections:

  • Type-hints are good
  • Type-hints have improved (… but there is still a long road to go)
  • Enforcing type-hints

He also covers some of their own best practices when it comes to type hinting in their code and shares a phpstan package that they use to enforce typing and formatting based on their own standards.

tagged: typehint bestpractice visualdebt package phpstan

Link: https://www.thecodingmachine.com/type-hint-all-the-things/

Russell Walker:
Is Best Practice Actually Poor Practice? Dependency Injection, Type Hinting, and Uni
Apr 05, 2017 @ 18:26:03

Russell Walker has a post to his site sharing his thoughts defending dependency injection, type hinting and unit testing against some of the common objections.

I've recently been in discussion with a colleague who thinks that dependency injection (DI) is over-used and, in cases where the dependency is a concrete class, unnecessary (in the latter case, he advocates simply creating new objects on the fly).

[...] In my opinion, this line of thinking is misguided, but he sent through some links to pages that he felt supported his point of view (including Tony Marston's rant on DI, and the Laravel documentation about 'facades' - which are actually used as an alternative syntax for the service locator [anti-]pattern). I genuinely wanted to understand the reasoning behind his point of view, as it flies in the face of just about everything I have ever read regarding best practice in PHP development. After reading those resources he sent though, I began to notice some misconceptions about what unit testing actually is, as well as confusion about the difference between code that is "strongly typed" (usually good) and "tightly coupled" (usually bad), and also a tendency to blame the wrong thing when problems arise.

He then breaks the rest of the post down into a few of the common objections and makes an attempt to set the record straight:

  • Not All Automated Tests Are Unit Tests
  • Using Mocks to Test in Isolation
  • What, Never Ever Create Objects on the Fly?
  • What About Those Laravel Facades?
  • Hidden Dependencies and Other Dangers
  • Strongly Typed is not Tightly Coupled

He ends the post with "another reason" that there could be issues with developers dismissing best practices in their development - a misunderstanding of the principle and how to correctly implement it.

tagged: bestpractice dependencyinjection typehint unittest opinion

Link: http://russellscottwalker.blogspot.co.uk/2017/03/is-best-practice-actually-poor-practice.html

Evert Pot:
PHP's callable typehint too loose?
May 07, 2015 @ 15:19:56

In his latest post Evert Pot wonders if the current implementation of the "Callable" type in PHP is too loose when it comes to what it will accept as a valid callable resource.

PHP got support for closures in version 5.3, and in PHP 5.4 we got support for a callable typehint. [...] All these little changes make it feel more comfortable to apply functional programming concepts to PHP, but occasionally we need to drop back to using less aesthetically pleasing code.

In his examples of "less aesthetically pleasing code" he shows a few different methods that work that aren't the typical closure or object arguments (like passing in an array of object+method name). He also shows an interesting option where you can use a string with a static method call (ex: "MyClass::method") and it will still be accepted. He points out that for this to work correctly in all situations, the call_user_func method should be used, not just calling the input directly.

tagged: callable typehint loose object method array variable iscallable calluserfunc

Link: http://evertpot.com/on-callables-and-closures/

PHPClasses.org:
Lately in PHP Podcast #48 - To TDD or Not TDD?
Jun 27, 2014 @ 16:38:37

On the PHPClasses.org site today Manuel Lemos has released the latest episode in their "Lately in PHP" podcast series: Episode #48 - To TDD or Not TDD?.

Lately the debate about whether you should use TDD or not in all software projects all the time has been very intense. [...] They also talked about the upcoming end of life release of PHP 5.3, getting information of parameter type hinting with reflection, using object methods on native data types, security problems of OAuth implementations, and the built-in support of Composer to access password protected repositories.

You can listen to this latest episode either through the in-page audio player, by downloading the mp3 or you can watch the live recording over on the PHPClasses YouTube playlist. A transcription of the recording is also provided as well as links to some of the topics mentioned.

tagged: phpclasses latelyinphp ep48 podcast tdd typehint oauth security composer

Link: http://www.phpclasses.org/blog/post/239-To-TDD-or-Not-TDD--Lately-in-PHP-podcast-episode-48.html

Wojciech Sznapka:
Type Hinting is important
Jun 12, 2014 @ 14:41:51

In his latest post Wojciech Sznapka reminds us that type hinting is important in your PHP applications and can help provide more structure and better overall code practices.

One of my favorite PHP interview questions, is: what is Type Hinting and why it’s important? Putting definition in one sentence, Type Hinting is a way to define type of parameter in function signature and it’s a sine qua non to leverage polymorphism. [...] So given the fact, that Type Hinting is optional and we don’t need to specify types of parameters passed to the method – why bother? Answer is easy: well prepared method signatures defines your model and are part of the “contract” that your code reveals to its consumers. It also prevents many silly errors and keeps codebase clean and coherent.

He talks about the best practices on using type hinting including where to put them (in an interface or base class or child class?) and some of the pros and cons of each. He also points out that some practices around type hinting, like overriding the hint and calling the method with unexpected/variable input, should be avoided (see the L in SOLID).

tagged: typehint importance bestpractice liskov substitution principle solid

Link: http://blog.sznapka.pl/type-hinting-is-important

PHPMaster.com:
Lesser-Known "Features" of PHP's OO Model
Jul 22, 2013 @ 17:21:22

On PHPMaster.com there's a new tutorial from Lorna Mitchell about some of the lesser known OOP features that are built in to the PHP language. She talks about things like interface inheritance, private properties and autoloading and type hints.

The vast majority of today’s applications written in PHP are object-oriented, and in general the core OOP concepts are pretty well understood by PHP developers. This article pushes the boundary of your understanding and shows you some tricks, or potential pitfalls depending on your perspective, of OOP in PHP.

Besides the ones mentioned above, she also looks at abstract classes and their use as well as the use of "finally" to handle the cleanup after exceptions.

tagged: features oop model language private inheritance typehint finally

Link: http://phpmaster.com/lesser-known-features-of-phps-oo-model

PHPEasy.co.uk:
Tutorial: Type Hinting in PHP
Aug 01, 2012 @ 17:14:35

On the PHPEasy.co.uk site there's a quick new tutorial posted about type hinting in PHP - how to use it and why you should use it in your code.

Type hinting allows you to tell a function which data type to accept for its arguments. When you call a function, if a type hint is present, the argument passed will be checked to make sure it is of the type specified. If a function has control over what it accepts as an argument, then it is more likely that the code within the function will have the data it needs to perform the task it is intended for.

He includes two code examples - one not using a type hinting on the parameters (assuming the correct arguments) and another forcing the input of the "PrintGuitar" method to be a "Guitar" object instance. You can find out more about type hinting in the PHP manual.

tagged: tutorial typehint example code beginner

Link:


Trending Topics: