Section III - Define a class - Classes and Objects in PHP5 [3]
Author: Leon Atkinson translation: Haohappy Source: Beyond the PHP / * ------------------------------------ ------------------------------------------ | = This article is HaohappY << CORE PHP Programming >> | = Classes and Objects Chapter Note | = Translate Main Personal Experience | = To avoid unnecessary troubles, please do not reprint, thank you | = Welcome criticism, hope and all PHP enthusiasts progress together! ----------------------------------------- ------------------------------------ * / Section 3 - Define a class when you declare A class that you need to list all variables and all functions of the object - referred to as attributes and methods. 3.1.1 shows a class configuration. Note that you can only declare the variables in braces ({}) or Functions. 3.1.2 shows how to define three properties in a class and two methods. 3.1.1 Class Name Extends Another Class {Access Variable Declaration Access Function Declaration} 3.1.2 Php // Define a tracking user Class Class User {// Property PUBLIC $ Name; Private $ Password, $ lastlogin; // method public function __construct ($ name, $ password) {$ this-> name = $ name; $ this-> password = $ Password $ this-> lastlogin = Time (); $ this-> accesses ;} // Get the last time function getLastLogin () {Return (Date ("M D Y", $ this-> lastlogin);}} // Create an instance of an object $ user = new user ("leon", "sdf123"); // Get the last time print ($ user-> getlastlogin (). "
n"); // Print User name Print ("$ us R-> Name
N ");?> When you declare attributes, you don't need to specify the data type. Variables may be integer, strings, or another object, depending on the actual situation. Increase when declaring properties Note is a good idea, marking the meaning of the property, and the data type. When you declare a method, what you do and the externally defined a function is the same. Method and attribute have their own namespace. This means you It is possible to securely establish a method with the same name of the class external function. Both will not conflict. For example, a class can define a method called Date (). But you can't name a method keyword, such as for Or while. The class method may contain the so-called Type Hint. Type Hint is another name of the class that passes the parameter to the method. If your script call method, PHP will generate a "fatal" (Fatal) Error. You may not give other types of Type Hint, just like integer, string, or Boolean. When writing, Type Hint should contain an array type still controversial .Type Hint is a test function The shortcut of the data type of the parameter or operator. You may always return this method. Verify that you enforce a parameter which data type must be, if you are intellectually. 3.2.1 Make sure the compiled class only generates a Widget instance. 3.2 .1 Php // component class widget {public $ name = 'none';