Essential Methods for PHP Classes: A Comprehensive Guide
☰Fullscreen
Table of Content:
- The functions which are declared in a class are called methods.
- A class method is exactly similar to PHP functions.
- Declaring a method in a class is an easy task, use one of the keyword public, protected, or private followed by a method name.
- public: The method can be accessed from outside the class.
- private: No access is granted from outside the class.
- protected: No access is granted from outside the class except a class that’s a child of the class with the protected property or method.
- A valid method name starts with a letter or underscores, followed by any number of letters, numbers, or underscores.
- The method body enclosed within a pair of braces that contain codes. The opening curly brace ( { ) indicates the beginning of the method code and the closing curly ( } ) brace indicates the termination of the method.
- If the method is not defined by the public, protected, or private then the default is public.
- Can access properties and methods of the current instance using $this (Format $this->property) for a non-static property.
Example:
After an object is instantiated, you can access the method of a class using the object and -> operator. In the following example customize_print() method will print a string with specific font size and color within an HTML paragraph element with the help of the PHP echo statement.
Syntax
font_size.";color:".$this->font_color.";>".$this->string_name.""; } } $f = new MyClass; echo $f->customize_print(); ?>
Now change the value of font_size, font_color, and the string and check what the method custimize_print() returns.
Syntax
font_size.";color:".$this->font_color.";>".$this->string_name.""; } } $f = new MyClass; $f->font_size = "20px"; $f->font_color = "red"; $f->string_name = "Object Oriented Programming"; echo $f->customize_print(); ?>
Another Example:
Example Code:
"; echo $this->color.""; echo $this->fabric."" ; echo $this->design.""; } } $dressObj = new Dress(); $dressObj->displayInfo(); ?>
Example of this
keyword
Example Code:
"; echo $this->color.""; echo $this->fabric."" ; echo $this->design.""; } Public function helloWorld(){ echo $this->displayInfo(); } } $dressObj = new Dress(); $dressObj->helloWorld(); ?>
Example of parameterized function
Example Code:
color; echo $this->fabric ; echo $this->design; } Public function helloWorld($number1, $number2){ return $number1 + $number2; } } $dressObj = new Dress(); echo $dressObj->helloWorld(20,30); ?>