Reputation: 454
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.
Upvotes: 2
Views: 945
Reputation: 88697
It is required that you reference the object to which the member belongs in order to access the member.
Every method call or property access is prefixed with $variable->
- $this
is a magic variable that refers to the current object instance. Its use is not optional.
This is (amongst other reasons) because not every function in PHP is a method, there are also global functions. If you reference a function without associating it with an object, it is assumed to be a global function.
As a side note, you should avoid the use of singletons in PHP - there is no performance/memory gain to be found from using them because each concurrently executing script is garden-walled into its own memory space.
Upvotes: 6
Reputation: 22592
Yes, you do have to use $this
when accessing class method's or variables.
You need to remember that PHP doesn't require that variables be declared, so image the following situation:
<?
class A {
public $a = 'Hello World!';
function hello() {
$a = 'hello';
echo $a;
}
}
$object = new A();
echo $object->hello();
$a
would be local scope and $this->a
would be the class variable.
Upvotes: 0
Reputation: 12069
The "pointer" (->
) != C++ pointer.
$this
means 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::$variable
or self::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->
or self::
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.
Upvotes: 2