Is there any reason to use the public
keyword before method and
member variable names in PHP, or is clarity the only reason some
people do it?
The reason is clarity.
Humans are coding this stuff. Humans need to read this stuff. And if a human cannot quickly decipher what is happening, lack of clarity can cause more issues.
It’s part of the reason that we also indent & properly format code. The language interpreter will eat up any code as long as the syntax is correct. Anything else—including comments—are placed there so us pieces of meat in front of a keyboard can actually make some sense of what is happening.
Using your pseudo-code example:
class SomeClass {
public $data;
public function someFunction() {
}
}
Look at how easy it is to read that and understand how it works! In comparison, look at this:
class cName { $d; function fName() {} }
Technically speaking both pieces of code should work the same. But what is $d
? And what is cName
? And what is fName
? The code would work in both cases, but who wants to spend any time untangling the second example. I mean, it works, right?
Clarity is the real key to good coding & development. This world programming & computer work is invisible—and sometimes—obtuse enough as-is. No reason to obscure how something works by just ignoring the fact that humans—not machines—create code.