" ; } function setTitle ( $par ){ $this -> title = $par ; } function getTitle (){ echo $this -> title . "
" ; } } ?>
The variable $ this is a special variable and it references the same object (eg itself).
Once you have defined your class, you can create as many objects as you like. The following example is how to create an object using the new keyword in PHP.
Part 2:
$ tieng Anh = new Books;
$ toanCaoCap = new Books;
$ tuTuongHCM = new Books;
Here, we have created 3 objects and these objects are independent of each other and they will have separate existence. In the next section, we see how to access member functions and handle member variables in PHP.
After creating the objects, you will be able to call member functions related to that object. A member function will only be able to handle member variables related to that object.
The following example illustrates how to set the title and price for 3 books by calling member functions.
Part 3:
$tiengAnh -> setTitle ( "English Grammar in Use" ); $tuTuongHCM -> setTitle ( "Toán cao cấp 1" ); $toanCaoCap -> setTitle ( "Tư tưởng Hồ Chí Minh" ); $tiengAnh -> setPrice ( 10 ); $tuTuongHCM -> setPrice ( 15 ); $toanCaoCap -> setPrice ( 7 );
Now call other member functions to get the value set in the above example:
Part 4:
$tiengAnh -> getTitle (); $tuTuongHCM -> getTitle (); $toanCaoCap -> getTitle (); $tiengAnh -> getPrice (); $tuTuongHCM -> getPrice (); $toanCaoCap -> getPrice ();
Save the above 4 sections of code (in the order above) in a file named test.php in htdocs , then open the browser and type in the address http:/// localhost: 8080 / test.php will result:
The constructor function is a special type of function that will be called automatically whenever there is an object creation from a Class. Therefore, we take advantage of this operation, by creating many things through constructor functions in PHP.
PHP provides a special function called __construct () to define a constructor. You can pass as many parameters as you want into this constructor.
The following example will create a constructor for Books class and it will initialize price and title for book at the time of creating this object.
Part 1.1:
function __construct ($ par1, $ par2) {
$ this-> price = $ par1;
$ this-> title = $ par2;
}
Now, we don't need to call separate function sets to set prices and titles. We can only initialize their two member variables at the time of creating the object. You check the following example:
Part 2.2:
$tiengAnh = new Books ( "English Grammar in Use" , 10 ); $toanCaoCap = new Books ( "Toán cao cấp 1" , 15 ); $tuTuongHCM = new Books ( "Tư tưởng Hồ Chí Minh" , 7 ); /* lấy các giá trị đã được thiết lập */ $tiengAnh -> getTitle (); $tuTuongHCM -> getTitle (); $toanCaoCap -> getTitle (); $tiengAnh -> getPrice (); $tuTuongHCM -> getPrice (); $toanCaoCap -> getPrice ();
Set the contructor (section 1.1) to the class (part 1) and then replace sections 2, 3 and 4 with part 2.2 (in the order above) in a file named test.php in htdocs , then open the browser and type the address http:/// localhost: 8080 / test.php will give the same result as above:
Like a constructor function in PHP, you can define a destructor function using the __destruct () function. You can free all sources with a destructor in PHP.
PHP class definitions can inherit from a parent class definition using the extends clause in PHP. Its syntax is as follows:
class Child extends Parent {
}
The effect of inheritance is subclass (subclass or inheritance) with the following characteristics:
Automatically have all member variable declarations of parent class.
Automatically have all member functions like in the parent class, which (by default) will work in the same method as when the function does in the parent class.
The following example inherits the Books class and adds some features as required.
class Novel extends Books { var publisher ; function setPublisher ( $par ){ $this -> publisher = $par ; } function getPublisher (){ echo $this -> publisher . "
" ; } }
Now, in addition to the inherited functions, the Novel class adds two member functions.
Function definitions in subclasses override the definitions with the same name in the parent classes. In a subclass, we can modify the definition of a function inherited from the parent class.
In the following example, the getPrice and getTitle functions are overwritten to return the values.
function getPrice (){ echo $this -> price . "
" ; return $this -> price ; } function getTitle (){ echo $this -> title . "
" ; return $this -> title ; }
Unless you specify, otherwise the properties (property) and the method of a class are public. That is, they can be accessed in the following three situations:
From outside the class in which it is declared.
From inside the class in which it is declared.
From within the external class that implements that class in which it is declared.
So far, we have seen all members are public members. If you want to limit the access of members of a class, then you define the class member as private or protected in PHP.
By specifying a member as private, you restrict access to the class in which it is declared. Private members cannot be referenced from classes that inherit the class in which they are declared and cannot be accessed from outside the class.
A class member can be specified as private by using the private keyword in front of the member.
class MyClass { private $car = "skoda" ; $driver = "SRK" ; function __construct ( $par ) { // các lệnh ở đây được thực thi mỗi khi // một instance của class // được tạo } function myPublicFunction () { return ( "Đây là một hàm Public!" ); } private function myPrivateFunction () { return ( "Đây là một hàm Private!" ); } }
When the MyClass class is inherited by another class by using extends, the function myPublicFunction () will be visible, like $ driver. The inheritance class will not recognize or access the function myPrivateFunction and $ car, because they are declared private.
A protected property or method is accessible in the class in which it is declared, as well as in classes that inherit from that class. Protected members are not available with the periphery of these two types of classes. A class member can be designated protected by using the protected keyword before that member in PHP.
Here is another version of MyClass:
class MyClass { protected $car = "skoda" ; $driver = "SRK" ; function __construct ( $par ) { // các lệnh ở đây được thực thi mỗi khi // một instance của class // được tạo } function myPublicFunction () { return ( "Đây là một hàm Public!" ); } protected function myPrivateFunction () { return ( "Đây là một hàm Protected!" ); } }
Interface is defined to provide a generic function name for implementers. Different implementors can deploy their interfaces according to their requirements. You can say, Interface is a framework that is implemented by the programmer.
As in PHP 5, it is possible to define an Interface, like:
interface Mail { public function sendMail (); }
Then, if another class implements that Interface, it's like:
class Report implements Mail { // lớp này cần định nghĩa hàm sendMail() }
A constant is something like a variable in which it holds a value, but it is actually more like a function, because a constant is irreversible. Once you declare a constant, it does not change.
Declaring a constant in PHP is quite easy, as done in this version of MyClass.
class MyClass { const requiredMargin = 1.7 ; // từ khóa const function __construct ( $incomingValue ) { // các lệnh ở đây được thực thi mỗi khi // một instance của class // được tạo } }
In this class, requireMargin is a constant. It is declared with the const keyword in PHP, and its value will not change in any situation. Remember, the constant name does not start with $, as in the variable name.
An abstract class is a class that cannot be initialized, only inherited. You declare an abstract class with the abstract keyword in PHP, as shown below.
When inheriting from an abstract class, all methods marked abstract in the parent class declaration must be defined by the subclass; In addition, these methods must be defined with the same visibility.
abstract class MyAbstractClass { abstract function myAbstractFunction () { } }
Note that function definitions within an abstract class must also be preceded by the abstract keyword. In PHP, it is not valid if you have defined the abstract function inside a non-abstract class.
Declaring class members or class methods is static making them accessible without a class initialization. A member declared as static cannot be accessed with a class object that has been initialized (although a method is static can).
Try the following example:
php class Foo { public static $my_static = 'foo' ; public function staticValue () { return self :: $my_static ; } } print Foo :: $my_static . "n" ; $foo = new Foo (); print $foo -> staticValue () . "n" ; ?>
PHP 5 introduces the final keyword, which prevents subclasses from overwriting a method by prefixing the keyword definition final. If the class itself is declared final, it cannot be inherited.
The following example creates Fatal Error: Cannot override final method BaseClass :: moreTesting ()
php class BaseClass { public function test () { echo "BaseClass::test() called
" ; } final public function moreTesting () { echo "BaseClass::moreTesting() called
" ; } } class ChildClass extends BaseClass { public function moreTesting () { echo "ChildClass::moreTesting() called
" ; } } ?>
Instead of writing a new constructor for the subclass, you can write it by calling the parent class constructor explicitly and then doing whatever it takes to initialize this subclass. Here is a simple example in PHP.
class Name { var $_firstName ; var $_lastName ; function Name ( $first_name , $last_name ) { $this -> _firstName = $first_name ; $this -> _lastName = $last_name ; } function toString () { return ( $this -> _lastName . ", " . $this -> _firstName ); } } class NameSub1 extends Name { var $_middleInitial ; function NameSub1 ( $first_name , $middle_initial , $last_name ) { Name :: Name ( $first_name , $last_name ); $this -> _middleInitial = $middle_initial ; } function toString () { return ( Name :: toString () . " " . $this -> _middleInitial ); } }
In this example, we have the Name parent class, have a constructor that takes two parameters, and a NameSub1 subclass, which has a constructor that takes three parameters. NameSub1's Constructor functions by calling its parent constructor explicitly using the syntax :: (passing its two parameters) and then setting an additional field. In the same way, NameSub1 defines the toString () function which overrides the parent class.
Example - A constructor can be defined with the same name as the name of a class, as in the example above.
Follow tutorialspoint
Previous article: PHP & XML
Next lesson: PHP for Programmer C