Midterms - Object Oriented Programming in PHP Flashcards
Defining a class
class keyword, class name, curly brace
<?php class Fruit { //Properties public $name; public $color; //Methods function set_name($name){ $this->name = $name; } function get_name(){ return $this->name; } } ?>
Objects of a class are created using the
new keyword
$apple = new Fruit ();
refers to the current object, and is only available inside methods.
$this keyword
<?php class Fruit { public $name; function set_name($name) { $this->name = $name; } } $apple = new Fruit(); $apple->set_name("Apple"); echo $apple->name; ?>
using $this keyword to change the value of a property
<?php class Fruit{ public $name; function set_name ($name){ $this->name = $name; } } $apple = new Fruit(); $apple->set_name("Apple"); echo $apple->name; ?>
ou can use the ____ keyword to check if an object belongs to a specific class:
instanceof
<?php $apple = new Fruit(); var_dump($apple instanceof Fruit);
allows you to initialize an object’s properties upon creation of the object
constructor
function_construct($name){ $this->name = $name; }
is called when the object is destructed or the script is stopped or exited
destruct Function
function_destruct(){ echo "The fruit is ($this->name)."; }
the property or method can be accessed from everywhere. This is default
public
the property or method can be accessed within the class and by classes derived from that class
protected
the property or method can ONLY be accessed within the class
private
When a class derives from another class.
The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods
Inheritance
An inherited class is defined by using the
extends keyword
~~~
class Strawberry extends Fruit {
}
~~~
Inherited methods can be overridden by redefining the methods (use the same name) in the child class
Overriding
can be used to prevent class inheritance or to prevent method overriding.
final keyword
~~~
final class Fruit{
}
~~~
cannot be changed once it is declared
costant