1. Member Variables - Member Variables are the variables that are defined inside a class. - These variables are invisible to the outside of the class. - We can access Member variables via member functions. 2. Member Functions - Member Functions are the functions that are defined inside a class. - We can access member functions by creating object of the class.
Class Member variables are called as properties, attributes or fields. Class Member variables can be defined as public, protected, or private. var is treated as public in PHP 5 onwards |
class className{ // Member variables public/private/protected/var $memberVariable1; public/private/protected/var $memberVariable2; .... public/private/protected/var $memberVariableN; // Member functions function memberFunction1() { } ... ... function memberFunctionN() { } }
$instance = new ClassName();
<?php class MyDetails { var $name; var $age; var $message; //member function with 3 arguments function showMyDetails($a,$b,$c) { $name = $a; $age = $b; $message = $c; echo "Name : $name <br>"; echo "Age : $age <br>"; echo "Message : $message <br><br>"; } } //creating object of class MyDetails $myDetails = new MyDetails; //calling member showMyDetails functions of class MyDetails $myDetails->showMyDetails("Mike","19","I love PHP!"); $myDetails->showMyDetails("Thomas","24","I love my iPhone!"); ?>
Output
Name : Mike Age : 19 Message : I love PHP! Name : Thomas Age : 24 Message : I love my iPhone!
function setVariableName($variableName) { $this->variableName = $variableName; }
function getVariableName() { echo $this->variableName; }
<?php class MyDetails { var $name; var $age; var $message; function getName() { echo "Name : ".$this->name ."<br/>"; } function setName($name) { $this->name = $name; } function getAge() { echo "Age : ".$this->age ."<br/>"; } function setAge($age) { $this->age = $age; } function setMessage($message) { $this->message = $message; } function getMessage() { echo "Message : ".$this->message ."<br/>"; } } $myDetails = new MyDetails; //Calling Setter Functions $myDetails->setMessage("I love PHP!"); $myDetails->setAge("19"); $myDetails->setName("Mike"); //Calling Getter Functions $myDetails->getName(); $myDetails->getAge(); $myDetails->getMessage(); ?>
Output
Name : Mike Age : 19 Message : I love PHP!