Starting a new PHP project and deciding that after a few years of PHP development, I’m thinking I should really start using PHP classes. I’m used to classes in the C++ world, so there’s a few things I’m not quite sure about when porting this knowledge over to PHP.
In C++, you can automatically access any class variables without a prefix, in PHP, it appears that you need to prefix all such accesses (variables and function) with this->. I know what this is (or at least I think so, a pointer to the current class instance), but I’m not sure whether its required or preferred, or if there is any alternatives. My class will be using other functions within the same class (ie, itself) fairly heavily, so having to type this-> every time is going to get time consuming quite quickly.
The classes themselves are likely to be singletons, so I’m not sure whether to actually use a class, or just prefix the functions with an identifier.
The “pointer” (
->) != C++ pointer.$thismeans the current class and instance. All variables are accessed by using$this->variable;or$this->function();.Static variables, and functions can be accessed using
self::$variableorself::function()Outside the class instance, you must indicate the class instance:
$foo->variable;or$foo->function();As far as I know, there is no way to access public/private/static/constant variables inside the class without using
$this->orself::In reference to using an object of functions… up to you. Are you planning on expanding the code later to add more functions? Are all the functions somewhat related? If they are singleton functions, there is no harm in just writing a function instead of a class. It really just depends on what you are trying to accomplish.