Class properties allow your objects to store data and class methods allow your objects to perform tasks.
What are Class Methods
Methods are special functions declared within a class. As you might expect, a method declaration resembles a function declaration. The function keyword precedes a method name, followed by an optional list of argument variables in parentheses. The method body is enclosed by braces,
Class Methods Scope
- Methods must be declared in the body of a class.
- Methods can accept a number of qualifiers, including a visibility keyword.
- Like properties, methods can be declared public, protected, or private.
- By declaring a method public, you ensure that it can be invoked from outside of the current object.
If you omit the visibility keyword in your method declaration, the method will be declared public implicitly
I am continuing my previous example of class Product. Today we will set and get class properties via class method.
I will recommend to set class properties via class methods because, There are a number of problems to setting property values without methods, as PHP lets you set properties dynamically, you will not get warned if you misspell or forget a property name.
Output of above code will be,
- I have taken three class properties in our above example.
- I have written three methods to set the value for these properties.
- I have written one class method to get the value of these properties.
- You can write three more methods to get the value of each property individually like getProductTitle.(), getProductName and getProductPrice().
- I have included public visibility keyword in my method getProduct(), so it can be called from outside the class.
- $this pseudo-variable: The $this pseudo-variable is the mechanism by which a class
can refer to an object instance.