Home > Backend Development > PHP Tutorial > Calling static properties and static methods in PHP object-oriented

Calling static properties and static methods in PHP object-oriented

WBOY
Release: 2016-07-29 09:01:00
Original
809 people have browsed it

Here is an analysis of the calling of static attributes and static methods in PHP object-oriented. Regarding their calling (whether they can be called and how to call them), you need to understand where they are stored in the memory, so that it is very easy to understand. Static properties and methods (including static and non-static) have only one location in memory (rather than static properties, there are as many properties as there are instantiated objects).

Example:

?

3. Static methods cannot call non-static attributes. Because non-static properties need to be instantiated and stored in the object;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?php

header("content-type:text/html;charset=utf-8");

classHuman{

staticpublic$name= "Little Sister";

public$height= 180 ;

staticpublicfunctiontell(){

echoself::$name; //Static method calls static properties, use self keyword

//echo $this->height;//Wrong. Static methods cannot call non-static properties

//Because $this represents an instantiated object, and here is a class, I don’t know which object $this represents                                                

}

publicfunctionsay(){

echoself::$name. "I spoke" ;

//Normal methods call static properties, also using the self keyword

echo$this->height;

}

}

$p1= newHuman();

$p1->say();

$p1->tell();//Object can access static methods

echo$p1::$name;//Object access static properties. You cannot access $p1->name like this

//Because the memory location of the static attribute is not in the object

Human::say();//Wrong. An error occurs when the say() method has $this; the result can be obtained without $this

//But php5.4 or above will prompt

?> ,Static methods can call non-static methods, using the self keyword. In PHP, after a method is called self::, it is automatically converted into a static method;

The above introduces the calling of static properties and static methods in PHP object-oriented, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template