Showing posts with label simple class. Show all posts
Showing posts with label simple class. Show all posts

Tuesday, February 18, 2014

PHP - Access modifiers - 1


PHP - Access modifiers

 Access modifiers are used to access class members (variables and methods).

Acess modifiers are,

*  Public
*  Private
*  Protect

 Public variable and method can accessible from anywhere .

 Private members only accessible inside the class not the inherited class.

 In other terms private access control is used to maintain encapsulation functionality.

Protected members can only access from derived classes.


class Person
{
 public $name;
 protected $age;
 private $phone;
 
 function setName($name)
 {
  $this->name=$name;
 } 
 
 function getName()
 {
  return $this->name;
 }
 
 function setAge($age)
 {
  $this->age=$age;
 }
 

 function getAge()
 {
  return $this->age;
 }

 function setPhone($phone)
 {
  $this->phone=$phone;
 } 

 function getPhone()
 {
  return $this->phone;
 }


}

$person = new Person;



$person->setName('Sivanthi');
$person->setAge(28);
$person->setPhone('95******53');
echo $person->getName();  // output is  Sivanthi

echo $person->getAge();  // output is  28

echo $person->getPhone();  // output is  95******53

echo "Person Name is ".$person->name;  // output is Person Name is Sivanthi

echo "Person Age is ".$person->age; // Cannot access protected property Person::$age

echo "Person Phone is ".$person->phone; // Cannot access protected property Person::$phone


So we cannot directly access private and protected members from a class,

instead of we can use setters and getters to access those variables.


Monday, February 17, 2014

PHP OOPS Part - 1 - Simple class


PHP one of the Fast growing web programming language. It contains object oriented feature for robust and complex projects design. let us create a simple class in php.
class Product
{
  public $product_id;
  public $product_name;

  public function getProduct()
  {
     echo "Product Name is ".$this->product_name.
  }
  
}

now we need to instantiate the class already created. steps are,
$productobject = new Product;

$productobject->product_name = "Colgate";

$productobject->getProduct();

The output is Product Name is Colgate
Explanation
* class keyword for create class * Product is the name of class
* $product_id and $product_name are class members (public)
* getProduct() is a public access method.
* $productobject = new Product;
new operator is used to instantiate the class
* $productobject->product_name = "Colgate";
the above line assign colgate as product name.
* $productobject->getProduct();
The above line call method getProduct from product class.