Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP classes - is it preferable to use normal variables instead of properties?

Tags:

oop

php

class

For my latest website I’ve been trying to use classes. Mainly to teach myself more about OOP and learn through experience.

Whenever I needed a ‘variable’ within my class I created a property, for instance:

class someClass
{

var $valueToUseHere; // Only used internally - can I just use a variable?

    public function doStuff()
    {
        $this->valueToUseHere = 60;
    // Do more stuff here...
    }

}

It is only now when I’ve been looking more into the code and trying to do some optimisation that I’ve noticed that my functions and classes are passing around some large objects. A lot of that bulk could be stripped away if I made all the properties that are only used inside the class into normal variables.

Are properties only used for variables that are needed outside the class and is it then acceptable to just use ‘normal’ variables within the class itself ?

Sorry if this question illustrates a lack of understanding on the subject. Unfortunately, this is where my learning is up to at this point. I’ve done some searching around “class properties vs variables” etc but not found a comprehensive answer to this.

Many thanks

like image 505
John T Avatar asked Dec 24 '22 18:12

John T


1 Answers

It's somewhat vague what you're asking, but if valueToUseHere is not used outside of doStuff, then don't make it a property!

class someClass {

    public function doStuff() {
        $valueToUseHere = 60;
        // Do more stuff here...
    }

}

If there's no reason to share that value with other methods of the class or with the outside world, then there's no reason to clutter up your object with all sorts of properties. Not only may this cause tricky bugs with preserved state, it also forces you to be unnecessarily careful with your variable names across all object methods.

like image 149
deceze Avatar answered Feb 01 '23 16:02

deceze