I was reading a book about PHP when I ran into a strange part of code:
class Employee {
public function show() {
echo "show launched\n";
}
}
Employee::show();
I came from C++ so I was going to bet this code wouldn't work. This is why I tested it.
And it worked, showing "show launched" (omg, am I drunk?)!
It seems to be breaking the concept that method of class can be called without instantiation of class.
Thanks in advance.
Addition: Just a notice.
I found that in this book. Pages 178-179 and it's given as correct example (if I'm right)
Yeah that would work but with a warning. You may have turned off your error reporting
on PHP by the way...
Strict standards: Non-static method Employee::show() should not be called statically
Adding a static
keyword before the function definition would make the warning dissappear.
Below code works without a warning..
<?php
class Employee {
public static function show() { //<----- Added the static keyword.
echo "show launched\n";
}
}
Employee::show();
It seems to be breaking the concept that method of class can be called without instantiation of class.
Yeah that is correct, that's why you are getting a pretty clear cut warning as I showed you earlier. You know what a warning does right ? ;). Something that should not be done.
From the PHP Docs..
Calling non-static methods statically generates an E_STRICT level warning.
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With