Start to understand the objects in the PHP V5

Source: Internet
Author: User
Tags access properties constructor functions interface key range require visibility
Object This article describes the basics of objects and classes in PHP V5 and inherits from the most basic concepts, primarily for experienced object-oriented programmers and readers who have not touched the object.

As a PHP programmer, you definitely know variables and functions. But classes and objects can be another thing. Without defining a single class, you can create a perfect system. But even if you decide not to use object-oriented programming in your own code, you may still need to understand object-oriented programming. For example, if you use a Third-party library, such as a library that you can use with PHP Extension and application Repository (PEAR), you will find yourself instantiating objects and calling methods.

  What are classes and objects?

Simply put, a class is a separate block or bundle consisting of variables and methods. These components are often combined to achieve a single responsibility or a set of responsibilities. In this article, you will create a class that collects methods for querying and populating dictionaries made up of items and values.

A class can be used directly as an easy way to organize data and functionality, just like a set of functions and variables. But using a class can ignore its existence. Class can be used to generate multiple instances in memory. Such an instance is called an object. Each object can access a set of identical functions (called methods in an object-oriented context) and a variable (called an attribute or instance variable), but the actual value of each variable is different in each object.

Consider a unit in the role-playing game--like a tank. Class may set a set of variables for the tank: defensive and offensive capabilities, range, health status, and so on. The class may also define a set of functions, including move () and attack (). When the system contains a tank class, the class can be used to generate dozens of or hundreds of tank objects, each of which potentially has its own health or range characteristics. Therefore, the class is the blueprint or template used to generate the object.

The easiest way to understand classes and objects may be to create some classes and objects.

First Class

You can create a class with the class keyword. In the simplest case, the class consists of a keyword class, a name, and a code block:

Class Dictionary {
}

A class name can contain any combination of letters, numbers, and underscore characters, but cannot begin with a number.

The Dictionary class in the previous example is completely legitimate, although it is of limited use. So how do you use this class to create objects?

$obj 1 = new Dictionary ();
$obj 2 = new Dictionary ();
$obj 3 = new Dictionary ();

At least formally, the instantiated object is similar to the calling function. For function calls, parentheses must be provided. As with functions, some classes require that you pass parameters for them. You must also use the New keyword. This tells the PHP engine that you want to instantiate a new object. The returned object can then be stored in a variable for future use.

Property

In the body of a class, you can declare a special variable called an attribute. In PHP V4, properties must be invoked with the keyword var. This is still the legal syntax, but primarily for backwards compatibility. In PHP V5, properties must be declared public, private, or protected. Can be in the keyword: can we have a little privacy here? Read the contents of these qualifiers in. But now in the example, all the attributes are declared public. Listing 1 shows a class that declares two properties.

Listing 1. A class that declares two properties

Class Dictionary {
Public $translations = Array ();
Public $type = "En";
}

As you see, you can declare attributes and assign values to them at the same time. You can use the Print_r () function to quickly browse the state of an object. Listing 2 shows that the Dictionary object now has more members.

Listing 2. Dictionary Object List

$en = new Dictionary ();
Print_r ($en);

If you run the script, you will see the output of the following objects:

Dictionary Object
(
[Translations] => Array
(
)
[Type] => En
)

You can use the object operator-> to access common object properties. So $en->type represents the $type properties of the Dictionary object referenced by the $en. If you can access a property, it means you can set and get its value. The code in Listing 3 creates two instances of the Dictionary class--in other words, it instantiates two Dictionary objects. It changes the $type properties of an object and adds translations of two objects:

Listing 3. Create two instances of the Dictionary class

$en = new Dictionary ();
$en->translations[' tree '] = "tree";
$FR = new Dictionary ();
$fr->type = "FR";
$fr->translations[' tree '] = "Arbre";
foreach (Array ($en, $FR) as $dict) {
print ' type: {$dict->type} ';
Print "tree: {$dict->translations[']}\n";
}

The script output is as follows

Type:en Tree:tree
TYPE:FR Tree:arbre

So the Dictionary class is now more useful. A single object can store different combinations of key values, as well as a flag that tells the client more about the Dictionary.

Although the Dictionary class is currently about the same as the wrapper of an associative array, there are some clues to the functionality of the object. At the moment, we can now well represent our sample data, as shown in Listing 4.

Listing 4. Sample Data

$en = Array (
' Translations ' =>array (' tree ' => ' tree '),
' Type ' => ' En '
);
$FR = Array (
' Translations ' =>array (' tree ' => ' arbre '),
' Type ' => ' Fr '
);

Although the data structure accomplishes the same purpose as the Dictionary class, it does not provide a guarantee of the structure. If you pass the Dictionary object, we know that it has $translations attribute. However, if it is an associated data, there is no such guarantee. This fact makes similar $fr [' translations '] [' tree ']; queries, unless the code that makes the query determines the origin of the array. This is the focus of the object: the type of object is the guarantee of its characteristics.

Although there are advantages to storing data with objects, you may not feel a bit. objects can be things, but the key is that they can do things.

Method

Simply put, a method is a function declared in a class. They are usually (but not always) invoked through object instances using object operators. Listing 5 Adds a method to the Dictionary class and calls the method.

Listing 5. To add a method to the Dictionary class

Class Dictionary {
Public $translations = Array ();
Public $type = "En";
function summarize () {
$ret = "Dictionary type: {$this->type}\n";
$ret. = "Terms:". Count ($this->translations). \ n ";
return $ret;
}
}
$en = new Dictionary ();
$en->translations[' tree '] = "tree";
Print $en->summarize ();

It provides the following output:

Dictionary Type:en
Terms:1

As you can see, declaring the Summarize () method is the same as declaring any function, except that it is declared in a class. The summarize () method is invoked by using the object operator with the Dictionary instance. The summarize () function accesses a property to provide a brief description of the object's state.

Note the use of a new feature for this article. $this pseudo variables provide a mechanism for objects to reference their own properties and methods. Outside of an object, you can use a handle to access its elements ($en in this case). Inside the object, there is no such handle, so you must turn to the $this. If you find $this a bit confusing, try replacing it with the current instance in your mind when you encounter it in your code.

Classes are typically represented in a diagram using the Generic Modeling Language (Universal Modeling language,uml). The details of UML are beyond the scope of this article, but this is a good way to visualize class relationships. Figure 1 shows the Dictionary class represented in UML. The class name is at the top level, the attribute is in the middle, and the method is at the bottom.

Figure 1. Using UML to display the Dictionary class

Constructors

The PHP engine recognizes many "magic" methods. If a method is defined, the PHP engine will automatically invoke these methods when the appropriate situation occurs. The most commonly implemented method is the constructor method. The PHP engine calls the constructor when instantiating the object. All the basic setup code for the object is placed in the constructor. In PHP V4, you create a constructor by declaring a method with the same name as the class. In V5, you should declare a method called __construct (). Listing 6 shows the constructor that requires the Dictionaryio object.

Listing 6. Constructors that require Dictionaryio objects

Class Dictionary {
Public $translations = Array ();
Public $type;
Public $dictio;
function __construct ($type, Dictionaryio $dictio) {
$this->type = $type;
$this->dictio= $dictio;
}
//...

To instantiate a Dictionary object, you need to pass the type string and the Dictionaryio object to its constructor. Constructors use these parameters to set their own properties. The following code shows how the Dictionary object can be instantiated: $en = new Dictionary ("en", New Dictionaryio ());
The Dictionary class is now more secure than before. All Dictionary objects have already been initialized with the required parameters.

Of course, some people are not prevented from subsequently changing the $type property or setting the $dictio to null. Thankfully, PHP V5 can help you achieve this.

Keyword: Can we have a little privacy here?

The Public keyword associated with the property declaration has been seen earlier. This keyword represents the visibility of the property. In fact, the visibility of an attribute can be set to public, private, and protected. Properties declared as public can be written and read outside the class, and properties declared private are only visible in the object or class context. Properties declared as protected can only be visible in the context of the current class and its subclasses. (In the Inheritance section, you'll see that these things work.) You can use the private property to actually lock the class. If you declare a property private and try to access it from outside the class scope (as shown in Listing 7), the PHP engine throws a fatal error.

Listing 7. Attempt to access properties from class scope external

Class Dictionary {
Private $translations = Array ();
Private $dictio;
Private $type;
function __construct ($type, Dictionaryio $dictio) {
$this->type = $type;
$this->dictio = $dictio;
}
// ...
}
$en = new Dictionary ("en", New Dictionaryio ());
$en->dictio = null;

The output is as follows: Fatal Error:cannot access Private Property
Dictionary:: $dictio in ...
Generally, you should declare most properties private, and then provide methods to get and set these properties as needed. This allows you to control the interface of the class, make some data read-only, clean or filter parameters before assigning them to attributes, and provide a clear set of rules for interacting with objects.

You modify method visibility in the same way that you modify property visibility by adding public, private, or protected to the method declaration. If your class needs to use some housekeeping methods that the outside world does not need to know, you can declare it private. In Listing 8, the Get () method provides the user of the Dictionary class with an interface for extracting translations. The class also needs to track all queries, thus providing a private method LogQuery ().

Listing 8. The Get () method provides an interface for users of the Dictionary class

function Get ($term) {
$value = $this->translations[$term];
$this->logquery ($term, $value, "get");
return $value;
}
Private Function LogQuery ($term, $value, $kind) {
Write Log information
}

Declaring LogQuery () as private simplifies the public interface and prevents the class from improperly calling LogQuery (). As with properties, attempting to invoke a private method from outside the containing class results in a fatal error.

[1] [2] Next page



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.