OBJECT ORIENTED PROGRAMMING Nguyễn Hữu Thể PHÁT TRIỂN ỨNG DỤNG WEB Content 1 Class 2 Visibility 3 Properties & Methods 4 Getter & Setter 5 Create objects 6 Constructor 7 Destructor 8 Inheritance 9 Abs[.]
PHÁT TRIỂN ỨNG DỤNG WEB OBJECT ORIENTED PROGRAMMING Nguyễn Hữu Thể Content 10 11 12 13 14 Class Visibility Properties & Methods Getter & Setter Create objects Constructor Destructor Inheritance Abstract class Interfaces Autoloading classes Anonymous functions Closures Namespace Class class ClassName { // Properties // Methods } Visibility (public, private, protected) − Three levels: • public • private • protected − By default, all class members are public Properties & Methods class Person { private $name; //public, protected private $age; public function show(){ echo $this->name " is " $this->age " years old!"; } } Create objects (Create a new instance of the class) − Using the new keyword: new ClassName() − For example: $person = new PerSon(); $person2 = new PerSon(); Getter & Setter PHP JAVA class Person { private $name; private $age; class Person { private String name; private int age; public String getName(){ return name; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public void setAge(int age){ this.age = age; } public function getName(){ return $this->name; } public function setName($name){ $this->name = $name; } public function getAge(){ return $this->age; } public function setAge($age){ $this->age = $age; } } } class Person{ private $name; private $age; Ex: Person.php public function getName(){ return $this->name; } public function setName($name){ $this->name = $name; } public function getAge(){ return $this->age; } public function setAge($age){ $this->age = $age; } public function show(){ echo $this->name " is " $this->age " years old!"; } } $p = new Person(); $p->setName("Nguyễn Văn A"); $p->setAge(18); echo $p->getName() " is " $p->getAge() " years old."; //echo "{$p->getName()} is {$p->getAge()} years old."; $p->show(); set() method class SetName { public function set($variable, $value) { // echo $variable; echo "My " $variable " is " $value "\n"; } } $obj = new SetName (); $obj->Name = ‘Tom'; $obj->Name = ‘Jerry'; My Name is Tom My Name is Jerry get() method class GetName { public $type = 'chocolate'; public $choctype = array ( 'milk' => 0, 'dark' => 1, 'plain' => ); public function wrap() { echo 'Its a wrap'; } public function get($index) { echo '$choctype property with index of: ' $index ''; return $this->choctype [$index]; } } $candy = new GetName (); // set a non existant property echo 'Value of property is: ' $candy->milk; $choctype property with index of: milk 10 Value of property is: ... show(){ echo $this->name " is " $this->age " years old!"; } } $p = new Person(); $p->setName( "Nguyễn Văn A"); $p->setAge(18); echo $p->getName() " is " $p->getAge() " years old."; //echo