Johannes Ott wrote on 11/03/2015 16:46:
Am 11.03.2015 um 17:21 schrieb Rowan Collins:
My reasoning is that code that is ambiguous is hard to read. If "$foo"
can mean either "a local variable called $foo" or "a property of the
current object called $foo", then you have to know which it is in order
to understand what code is doing.
So for clean code rules you should do smaller methods if you can't even
see clearly whether you declared $foo locally or not.
True, but again, PHP doesn't give you a way of declaring that a variable
*is* local, so it would be impossible in isolation to tell if $rate in
this example is a property or just a temporary variable:
public function setRatePercentage($rate_percent) {
$rate = $rate / 100;
$processed_amount = $amount * $rate;
}
This is not about "a strict OOP-world", incidentally, it's about scoping
rules. Java imports object properties into the scope of each method, PHP
does not. Even if properties had to be declared (which is probably a
good idea), local variables still wouldn't be - in Java, the fact that
it's not declared locally means it *must* be coming from somewhere else.
No if it is not declared locally it doesn't mean it's coming from
somewhere else, but it means it is coming from one of the next higher
scopes which is normally the Object.
By "somewhere else", I meant "somewhere other than the local scope", so
we're both saying the same thing here.
I also know that when I was first learning Java at school, it confused
me immensely which variables I was allowed to access in static contexts.
In PHP, that's simple - if you can't access $this, you can't access any
of it's properties.
I'm not talking about beginners code, but about professional clean code.
If you're doing as a beginner you can still use the $this keyword to
make it clearer code for you to understand.
A lot of beginners start by reading other people's code, or get jobs
working alongside experts. Having completely different styles of
programming for experts and beginners harms collaboration.
It is often observed that code is read much more often than it is written.
If you want to resolve the scope of a method to the current object
without using the variable $this, you can also use the "static" keyword;
these are equivalent:
$this->some_function(...);
static::some_function(...);
// http://3v4l.org/E0XYs
I don't care whether I use $this-> or static:: as keyword. In this case
I would even prefer $this-> because static in instance context is in my
opinion really confusing.
I agree, I was just demonstrating that we already have a keyword syntax,
for scope resolution, as well as a well-behaved variable, $this.
Regards,
--
Rowan Collins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php