Another interesting discovery I've made is how Python uses 'self' which is very different in how PHP uses it. It is worth saying that 'self' in Python is not a keyword however, its usage is by convention. In other words it can be replaced by any other word like "this or that". Even though it is not a keyword, developers are encouraged to stick to the use of 'self' for clarity and consistency with other Python code.
With that said, let's compare and contrast how the same word means something completely different in both Python and PHP.
You will be interested to know that the use of "self" is encountered only when writing object oriented code in both languages, and it turns out that is the only similarity.
What is 'self' in Python?
When implementing a class in Python, the class constructor(__init__) is expected to receive the instance of the class as its first argument, and by convention this is done by passing the word "self". Also all methods of the class are required to receive "self" as its first or only argument. So when implementing functions developers are required to state 'self' as the first argument of the function. Once passed it can then be used to access the properties and methods of the class within the function's scope.
Don't pass 'self' as the first argument when you make a function call
During function calls, developers are not required to pass 'self' to the function as this is handled by the python engine behind the scenes.
Below is an example of a Cylinder class showing how "self" is used.
So what is 'self'? It simply means this instance of the class. The reason for that is you can have many instances of a class. In other words many objects can be created from the class containing the same properties and attributes. So when you create many instances of the class, during code execution the engine need to know which instance of the class you are referring to, and it knows this by the use of 'self'.
What is 'self' in PHP
The first distinction to establish here is the fact that unlike Python, in PHP 'self' is actually a keyword and cannot be changed to something else. In PHP OOP 'self' is used to refer to the class itself and not the instance of the class. Actually, PHP introduces the '$this' keyword to refer to the instance of a class.
Use case
It is used to refer to class constants, and to access static properties and methods of a class. Checkout the below example.
Summary
In Python 'self' is used to refer to the instance of class whereas in PHP 'self' refers to the class itself and it is used in the context of static members or constants.
In Python 'self' is used as the first parameter in the __init__
constructor and other class methods. This is not the case in PHP
Lastly, 'self' is just a convention in Python and can therefore be changed whereas in PHP it is a keyword that cannot be changed.