Properties and Methods in PHP

Properties and Methods in PHP - Each class has properties that are sometimes called attributes. Properties of a car such as color, size, price and so on. In the class, properties are represented by a variable. For example $color, $price, and so on.
Method is something that can be done by object. The method in PHP is synonymous with a function. Methods that may belong to a car for example, methods to turn the car, run the car, stop the car, and so forth.
Naming properties and methods have the same rules as naming a variable or function. However, based on the convention, naming properties and methods must use camel caps, where each word begins with uppercase except the first word, each word is combined with no spaces or under-scores(_).
Properties and Methods in PHP

Adding Properties (Variables)
Consider the example of defining the class and its properties, as follows:
class Car
{
var $color;
var $brand;
var $price;
// Add method definitions here
}

The class variable can also be directly initialized with a value. However, initialization variables should not contain arithmetic operations or other operations. Consider the following example:
class Car
{
var $color = "Red";
var $brand = "HONDA";
var $price = "15000000";
// Add the method definitions here
}

Adding Method
Method name is basically up (follow the rule variable name). However, do not use method names that begin with two under-scores (__) ie __construct(), __destruct() and __clone() because these three functions have their own meaning in PHP.
Here's an example of adding a method:
class Car
{
var $color = "Red";
var $brand = "HONDA";
var $price = "15000000";
function changecolor ($Newcolour)
{
$this-> color = $Newcolour;
}
function colorappears ()
{
echo "
The color of the car : " . $this->color;
}
}

Adding Constructors
Constructor is a special method that will be automatically executed when object is formed. The constructor method usually contains the default value of each property (variable). In one class there can be only one constructor and the constructor does not have to exist. To create a constructor, simply by defining a function with the name __construct ().
Here is an example.
class Car
{
var $color;
var $brand;
var $price;

function __construct()
{
$this->color = "Red";
$this->brand = "HONDA";
$this->price = "15000000";
}
function changecolor ($Newcolour)
{
$this-> color = $Newcolour;
}
function colorappears ()
{
echo " The color of the car : " . $this->color;
}
}

That's my article about Properties and Methods in PHP. Hopefully the article can increase our knowledge in learning the php programming language.

Comments