code is as follows |
copy code |
Class Child { private $parent; function __construct ($parent) { $this->parent = $parent; } function getnationality () { & nbsp; return $this->parent->nationality; } } $parent = new Parent (' Hispanic '); $child = new Child ($parent); |
In the PHP tutorial, a class is used to complete the information encapsulation, and the syntax for defining classes in PHP is:
Class Class_name//In object-oriented programming classes, the first character of the custom class is capitalized and must conform to the naming rules for the variable.
{
A collection of functions and variables
}
?>
When you define a class you can define your own preferences, but it's best to keep a standard so that it's more efficient to develop.
Data members are defined in a class using the "var" declaration, which is not typed until the data member is assigned a value. A data member can be an integer, an array, an associated array (associative array), or an object.
The following is a practical example of a class definition:
The code is as follows |
Copy Code |
Class student { var $str _name; Name var $str _sex; Gender var $int _id; School Number var $int _english; English results var $int _maths; Math Scores } ?> |
This is a simple example of a very common definition class, used to show students ' academic achievement, class name Student,student class contains a student's basic attributes: Name, gender, number, English score and math grade.
function we call the functions defined in a class, when you access a class member variable in a function, you should use $this->var_name, where var_name refers to the variable declared in the class, otherwise it can only be a local variable for a function. We first define a function of input () to assign an initial value to an object in the instance:
The code is as follows |
Copy Code |
function input ($name, $sex, $id, $englis, $maths) { $this->str_name= $name; $this->str_sex = $sex; $this->int_id = $id; $this->int_englis= $english; $this->int_maths= $maths; } |
Now we're going to define a function called "showinfo ()" To print the student's basic information:
The code is as follows |
Copy Code |
function Showinfo ()//define SHOWINFO () functions { Echo ("Name: $this->str_name ”); Echo ("Sex: $this->str_sex ”); Echo ("School Number: $this->int_id ”); Echo ("English score: $this->int_english ”); Echo ("Math score: $this->int_maths ”); } |
A well-defined class must use the new keyword to generate the object:
$a _student=new student;
For example, to create an instance of an object named $wing, and assign it, you can use the following code:
$wing =new student; Use new keyword to generate object
$wing->input ("Wing", "male", 33,95,87);
Enter Wing's name, gender, study number, English score, Math score, and the name and gender are character variables, so double quotes are required, and other values are not required.