PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP Object Oriented ProgrammingPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP Interfaces

PHP OOP Methods

Methods are used to perform actions.

In Object Oriented Programming in PHP, methods are functions inside classes. Their declaration and behavior are almost similar to normal functions, except their special uses inside the class.

Let's remind the role of a function.

How to declare a method?

Let's declare a method inside a class named Example class to echo out a simple string that we give.


<?php
class Example {
	public function echo($string) {
		echo $string;
	}
}

We use the public keyword to make the method available inside and outside the class. You will learn more about this in the visibility chapter.

How to call a method?


$example = new Example();
$example -> echo('Hello World');

Result: Hello World

Explained:
The thing you need to understand is that we call methods on objects, not classes.

Changing a property value using methods

Let's implement the things we learned in the above example to our House class. Now we are going to change the color of the house. For ease, all the properties are removed from the House class, except $primaryColor.

By default the color of the house is black. We need to change it to another one.


<?php
class House {
	public $primaryColor = 'black';
	public function changeColor($color) {
		$this -> primaryColor = $color;
	}	
}

// creates an object from the class
$myHouse = new House();

# black (default value)
echo $myHouse -> primaryColor;

// change the color of the house
$myHouse -> changeColor('white');
	
# white
echo $myHouse -> primaryColor;

Run Example ››

In this example, we have used $this keyword. The next chapter describes more about it.

Facebook Twitter