Properties and methods in PHP OOP

Both properties and methods work.

Question:which option is correct and why?


Answer 1, authority 100%

both options are purely ideologically incorrect due to the stupid naming of class methods, the method is called getNumA, so it is not clear why instead of return $this->awe see initialization class fields…

—————————————————– ————————————————– —————————————–

Always and everywhere, any methods whose name begins with getmust be public, moreover, it is understood that these methods are used to obtain some value, respectively, they must return something . For example:

class User {
    private $_name;
    public function __construct($name = false) {
        if($name) {
           $this->_name = $name;
        }
    }
    public function getName(){
        return !empty($this->_name) ? $this->_name : '';
    }
}
$user = new User('');
$guestUser = new User();
echo $user->getName(); // -> 
echo $guestUser->getName(); // -> 

—————————————————– ————————————————– —————————————–

Well, now you can already talk about programming directly.

It’s natural to pass class fields to methods of the same class in the same class 🙂 – it’s stupid and the most it will lead to is confusion.

True, I would like to note that, sometimes, this makes sense, for example, our class has a public method that, of course, can take some parameters “from the outside”, then, of course, it’s correct (read for working: ) ) – there will be a second option.

PS: I would like to add that it is customary to name private fields starting with an underscore, i.e. not $a, but $_a, the same can be said about private methods.


Answer 2, authority 100%

It makes no sense to pass a variable that you use from the same class to a method (unless, of course, you mean changing this logic in the future). This only introduces confusion into the code, since in the future you may forget what the argument is, and there will certainly be a temptation to pass anything other than the private value of this class. Based on the current intent of the code, this would be a mistake.