Home > Article > Backend Development > Section 6 - Accessing properties and methods - Classes and Objects in PHP5 [6]_PHP Tutorial
Section 6 - Accessing properties and methods
The properties of an object instance are variables, just like other variables in PHP. But you must use the -> operator to reference them. There is no need to use the dollar sign $ before the attribute. For example, the line that prints the name attribute of the User object in 6.1.
can be used together ->, if the attribute of an object contains an object, you can use two A -> operator to get the properties of an internal object. You can even use double-referenced strings to place these expressions. See the example in 6.5, the room property of the object House contains a set of Room objects.
Accessing methods is similar to accessing properties. The -> operator is used to point to the method of the instance. In Example 6.1, getLastLogin is called. The method execution is almost the same as the function outside the class.
If a class Inherited from another class, the properties and methods in the parent class will be available in the child class, even if they are not declared in the child class. As mentioned before, inheritance is very powerful. If you want to access a For inherited properties, you only need to reference them as you would access your own properties of the base class, using the :: operator.
<?php class Room { public $name; function __construct($name="unnamed") { $this->name = $name; } } class House { //array of rooms public $room; } //create empty house $home = new house; //add some rooms $home->room[] = new Room("bedroom"); $home->room[] = new Room("kitchen"); $home->room[] = new Room("bathroom"); //show the first room of the house print($home->room[0]->name); ?>
<?php class Animal //动物 { public $blood; //热血or冷血属性 public $name; public function __construct($blood, $name=NULL) { $this->blood = $blood; if($name) { $this->name = $name; } } } class Mammal extends Animal //哺乳动物 { public $furColor; //皮毛颜色 public $legs; function __construct($furColor, $legs, $name=NULL) { parent::__construct("warm", $name); $this->furColor = $furColor; $this->legs = $legs; } } class Dog extends Mammal { function __construct($furColor, $name) { parent::__construct($furColor, 4, $name); self::bark(); } function bark() { print("$this->name says woof!"); } } $d = new Dog("Black and Tan", "Angus"); ?>