- Classes and methods in PHP
- How to create a guest book in PHP - examples and commentary
- Data storage by means of DB in PHP
- Web-application development in PHP
- Base concepts in PHP programming for beginners and professional users
- Encapsulation in PHP
- Inheritance in PHP
- Polymorphism in PHP
- Constructors and destructors in PHP
- Modelling at a higher level of abstraction. Abstract classes and interfaces in PHP
First and foremost, it is necessary to understand that a class is not a set of functions or a container for variables, but abstract data type (ADT). PHP is not a strictly typified language, therefore for the beginning it is necessary to understand what are "simple" types. Integers (1, 45, 100, 378, etc.) have integer type. An array is also a type of data. For more details you can learn the documentation: http: // www.php.net/manual/ru/language.types.php. A class is also a type of data, but an object is an original variable of this type.
At a class creation it is necessary to understand a problem, which we want to present. Often a class construction is the process of modelling of the essence, which is necessary to transfer to a code. An object is a reflection of the essence that is described in a class form. In class modelling it is necessary to reveal those necessary parts of the essence, on which necessary actions will be made by means of methods. It means that necessary parts of the essence are fields of a class; they reflect data, which compile a general data type. By this an object type reminds data of an array type.
Methods carry out various actions on data. Methods should be designed in a way to work only with those data which are determined in a class. It is not recommended to define methods which influence on external data in any way. The so-called strategy of weak linkage implies that the less links there are between classes and external data, the easier it is to take a class from a system and use it again.
For example, the pack of cigarettes class consists of a packing and an array of cigarettes, so it is necessary to create methods which work only with a packing and cigarettes. There is no necessity to use methods by means of which we open a bottle of soda or even light a cigarette. Each class should realize only those actions which work with data of the class. Don't try to thrust all realization of the whole appendix into one class. For example, there is a site which consists of the main page, guest book, news pages, section of articles and links to friendly sites. Describe each section of a site by its own class or classes. The classes that reflect sections of a site can enter inheritance with each other. I.e. we represent a section as the essence, a separate type of data. Again I shall repeat, that in a class, modelling a news section, it is not necessary to define elements of other sections if there is no necessity. If it is required to present something from other sections, use inclusion. For example, on news page it is required to display headings of last articles. Define in a class of news a field of an articles class type and use methods of this type. Do not try to write the methods displaying articles headings in a class, modelling news. Define a necessary method in a corresponding class, a class that represents articles.
How to create a guest book in PHP - examples and commentaryNow let's get down to concrete examples. Let's try to create the simplest guestbook.
First what we need to do is to define the parts of the needed essence. These parts will be presented by visitor's name, his e-mail and his message proper.
Firstly, we have named essential parts of our data type. Secondly, fields are named with the private access modifier, which means, that it is possible to work with class fields only with the help of the same class methods. I will tell a bit later about access modifiers. Thirdly, we have named a method __construct($name, $email, $msg). This method is the designer of a class. About constructors and destructors will be told later, and now you should remember, that constructors are always carried out automatically first, before all other methods of a class, right after memory allotment for an object. Destructors are carried out the last, directly before the object destruction.
The fourth we have used the keyword $this. $this means the reference to an object, for which this or that design is realized. Unlike other programming languages, at the reference to members of a class, it is necessary to use $this: $this-> name and $name are two different variables.
Now let#145s dwell on how to address to an object fields. Let's realize methods, which will return proper values.
Now we can read data of a class from outside.
Data storage by means of DB in PHPHow to store data is the question that arises by a guest book development. Let's take advantage of MySQL database. We will add a new field of DataBase type, which is a special type for working with a DB. In the designer we'll carry out the process of initialization. We'll create methods for data acquisition from the base and filling of the base.
The method of reading (SELECT) is realized as follows: The method of values addition is realized as follows:
The first method returns an array of GuestBook objects, the second returns TRUE, in case data are added successfully, and FALSE if not.
In the first line of Select() method SQL base inquiry is created for all values access. In the second line the resultant table in the form of an array $dbArray is taken. The process itself will be described later. In the fifth line we create an array of GuestBook type objects, which comes back as a result. In order to address corresponding fields we have realized corresponding methods.
For the second method there is also a SQL-inquiry, but it is used to add data in the base (INSERT). If the inquiry is executed successfully, we return the truth (TRUE), otherwise - lie (FALSE).
Web-application development in PHPDeveloping a web-application with the help of OOP, it is necessary to remember about capability, which is always lower in comparison with the procedural approach. The Select method, returning values every time, demands reference to a new object of the DataBase type. If a thousand records is stored in the base, it will cause significant additional charge - processing of each record will demand creation of an additional DataBase object. Let's solve the problem. The first thing that comes into everybody's mind is not to initialize a field of a DataBase type, but to write the needed method, which initializes a $db field.
The parameter $db is a copy of a DataBase class. It is possible to do as follows: But to initialize the object again and again is not an optimal way. Practice has shown that it is more optimal to divide a similar class into two: in the first one we need to realize initialization of the essence, and in the second to name necessary methods for work with a database.
The difference here is obvious. First, we receive an array of objects using Select method, but now it contains only necessary data. Now on a thousand of GuestBook objects, only one object GuestBookDb is created. There is no necessity to store DataBase data in memory a thousand times. Secondly, the Insert() method changed a little. It has a parameter - a GuestBook type object - it is necessary for entering data in the base. As a result the load on server will decrease a little.
Base concepts in PHP programming for beginners and professional usersIn object-oriented programming there are three basic elements: encapsulation, inheritance, and polymorphism. The article doesn't set the purpose to give all-round examination of all OOP aspects. Here is briefly considered the essence.
Encapsulation in PHPEncapsulation is a concealment of realization. For users of a class it is unimportant how the class is realized, but it is essential what methods are available, i.e. what interface represents a class. We have already met encapsulation twice. In the first case we have named fields of a class as closed (private), i.e. we have hidden them from the public eye. It is also possible to make methods closed (private), so they will not be available for an external user, however they can be activated inside opened (public) methods of the same class. Closed methods are necessary to simplify opened methods, by breaking a complicated task into several simple ones. First of all it is necessary for reorganization of a code, for its convenient reading and understanding. In the second case it is also the closed field $db. We have assigned an internal variable the corresponding type of data, having hidden not only realization, but also an object creation process.
Inheritance in PHPWe have already come across the connection of classes with each other when declaring a variable of DataBase type. We have implicitly bound classes by means of inclusion. But what is the inheritance in its more common sense?
Inheritance is an expansion of an old class up to a new one by enhancement of functionality, i.e. the new class will contain the same methods (which, by the way, can change their realization) and properties as the former class.
A new class we call a descendant class, and the former, from which the inheritance goes, an ancestor class or a base class. First of all inheritance is used for hierarchical systems construction in which descendant classes develop base classes functionality. Inheritance can also be used for a change of logic of initial realization - i.e. for modification of an existing appendix.
Let's illustrate it with an example. It is necessary to expand the list of parameters which can be entered by a user in the guest book. Besides a name, email and messages users are able to enter the URL address and ICQ number. For this purpose it is not necessary to create a new class, we simply inherit the prepared realization from the GuestBook class.
As appears from the listing, old methods do not need to be realized, this way one of the major problems of the object-oriented approach - code reuse - is solved.
Please, pay your attention to the parent-constructor realization:: __construct($name, $email, $msg); - the official documentation says when the affiliated class reloads the methods which have been named in a parent-class, PHP does not carry out an automatic methods request belonging to a parent-class. This functional is assigned to a method, which reloads in an affiliated class.
By means of a keyword "extends" inheritance is also carried out. Now has come to change class GuestBookDb for work with new type of data.
In this case there is no necessity to overload the designer since it has remained constant. We have simply redefined necessary methods, changed the functional, having left their previous names. Using inheritance we can redefine any method, but sometimes we should forbid redefinition of methods and leave initial realization. For a similar case it is necessary to use a keyword 'final'. Let's consider an example.
If we started to redefine the PrintVar () method there would be a mistake. We can also name classes with a keyword 'final' if there will be a necessity to forbid inheritance from the current class.
Polymorphism in PHPPolymorphism is the ability to apply methods with identical names in a group of classes connected by inheritance.
Constructors and destructors in PHPA constructor. We have already come across constructors. Constructors, which are special methods in fact, are invoked each time at a class object creation, in which the constructor is specified. There can be no constructors in a class or just only one. Usually, a constructor is used for initialization of any class field, i.e. to define the initial condition of an object, for example, by means of methods activation, private as a rule. If a constructor contains some parameters, an object also should be invoked along with corresponding parameters. In case we name a method with parameters we should invoke it with the same quantity of parameters, and as it has been already said, a constructor is a special method which is invoked at an object creation. Therefore we should create an object together with parameters. Let's create an object for the class GuestBook.
If there was no constructors or a designer didn't contain any parameters, we would create an object as follows: We also know from the previous examples how to invoke constructors named in parental classes - parent:: __ construct ();
Destructor. A destructor is invoked at an object destruction. Destructor cannot contain parameters. As well as a designer, a destructor is also a special method with a special name.
__ destruct (). Usually, a destructor is used for memory cleaning: closing of a database connection, file closing, removal of unnecessary variables, etc. To call a destructor from a class-ancestor use the analogical way as with a constructor, - parent:: __ destruct ();
Modelling at a higher level of abstraction. Abstract classes and interfaces in PHPA programmer begins the project with an abstract model construction. We have already modelled the guest book, but at the lower level of abstraction. A class is an abstract data type, therefore the abstraction is of primary significance. We project the essence, but we do not want yet to touch upon realization, therefore we only do model sets of methods which are to work with data. At an initial stage we should only describe functionality of a class, leaving out details of realization. We should understand what we are to do on those data which we have included in the type. For the realization we need abstract classes, their abstract methods, and also interfaces.
If there are named abstract methods in a class, the class should be also declared as abstract. The abstract class can contain both usual methods and fields. It is impossible to create an object of an abstract class, but it needs to be redefined with the help of descendant classes. I.e. abstract classes serve as classes' prototypes, which inherit their basis. We should accept the rules of abstract classes. If we have named an abstract method with two parameters, in subsequent classes we should realize the same method with the same number of parameters.
Let's create an abstract class for GuestBookDb class; as for the SharedGuestBookDb class, we can inherit it from an abstract class as well as from GuestBookDb class.
Abstract classes are favourable when they contain less abstract realization as in our example. And if we need only abstraction, and it is also necessary to inherit a class from several abstract essences? As we remember we can inherit from one class only. Here come interfaces. In an interface it is possible to name without specifiers, including abstract. In the interface it is possible to define only abstraction of actions, i.e. methods which can be only public. We abstract visible realization. We should show the work of our class to other developers. Let's consider the interface in practice. We shall change a little our previous code.
We can inherit several interfaces at once. We are to improve our guestroom, add methods of updating of a database and sample of the certain record according to a concrete identification number.
We can simultaneously inherit both a class and an interface. Thus the class is inherited first. One interface can inherit another one applying a keyword 'extends'.
Here are the main peculiarities of the object-oriented script writing approach in the PHP language. We have not mentioned some topics, such as class static elements, processing of exceptions. When you learn to project classes and write OO code, these topics will be more comprehensible to you.





