Loading...

oops in php

Class Properties in php

  1. Variables to hold object values
  2. Also called: attributes,class variables,instance variables
  3. Define with var keyword,followed by $variable_name
  4. can set an initial value

Example

<?php
class Person{

var $first_name;
var $last_name;
var $employed=false;
var $country='none';
}
$customer = new Person;
$customer->first_name='Dilip';
$customer->last_name='Kumar';

echo $customer->first_name;//Dilip
echo $customer->country;//none

$customer->country='INDIA';
echo $customer->country;//INDIA

Functions for properties:

  1. get_class_vars($string):-Get the default properties of the class
  2. get_object_vars($object):-Gets the properties of the given object
  3. property_exists($mixed,$string):-Checks if the object or class has a property

File:class_properties.php 

<?php
class Student{
var $first_name;
var $last_name;
var $country='none';
$student1= new Student;
$student1->first_name='harish';
$student1->last_name='kumar';

$student2= new Student;
$student2->first_name='sha';
$student2->last_name='babu';

echo $student1->first_name."".$student1->last_name."<br>";
echo $student2->first_name."".$student2->last_name."<br>";

$class_vars=get_class_vars('Student');
echo "class vars:<br>";
echo'<pre>';
print_r($class_vars);
echo '<pre>';

$object_vars=get_object_vars()$student1
echo "object vars:<br>";
echo'<pre>';
print_r($object_vars);
echo '<pre>';
if(property_exists('Student','first_name'))
{
 echo 'property first_name exists in student class <br>';
}
else
{
 echo 'property first_name does not exists in student class <br>';
}
}

Output:

Harish kumar
sha babu
class vars:
Array
(
 [first_name]=>
 [last_name]=>
 [country]=>none
)
object vars:
Array
(
 [first_name]=>Harish
 [last_name]=>kumar
 [country]=>none
)
property first_name exists in Student class