oops in php
Static modifier in php
- Behaviors related to the class generally
- Not tied to a particular instance
- "class properties","class methods"
- Accessible directly from the class,without any instance
- use keyword static
Example
<?php
class Student{
static $grades=['Fresher','Junior','Senior'];
static function motto(){
return 'to learn php';
}
}
- Different syntax to reference static properties and methods
- Student::$grades,Student::motto()
- static methods cannot use $this
- self::$grades,self::motto()
- can be combined with visibility modifiers
Example:
<?php
class Student{
public static $grades=['Fresher','Junior','Senior'];
private static $total_students=0;
public static function count(){
return self::$total_students;
}
}
echo Student::grades[0];//Fresher
echo Student::$total_students;//error:cannot access private property
echo student::count();//0
- staic properties are not accessible from an instance
- static methods are accessible from an instance
- Bad practice:php5 warning,php7 deprecation notice
File:static_modifiers.php
<?php
class Student{
public static $grades=['Fresher','Junior','Senior'];
private static $total_students=0;
public static function motto(){
return 'to learn php';
}
public static function count()
{
return self::$total_students;
}
public static function add_student()
{
return self::$total_students++;
}
}
echo Student::grades[0].'<br>';
echo Student::motto().'<br>';
//echo Student::$total_students.'<br>';//error
echo Student::count().'<br>';
Student::add_students();
echo Student::count().'<br>';
?>