search
HomeBackend DevelopmentPHP TutorialHow to define classes and their member attributes and operations in PHP_PHP Tutorial
How to define classes and their member attributes and operations in PHP_PHP TutorialJul 13, 2016 am 10:39 AM
phpandandhowdefinitionobjectAttributesmemberoperateyesconceptofkindgather

Concept of class: A class is a collection of objects with the same attributes and operations. It provides a unified abstract description for all objects belonging to this class, which includes two main parts: attributes and operations. In object-oriented programming languages, a class is an independent program unit. It should have a class name and include two main parts: attribute description and operation description.


1. Class definition:

i. Class keyword definition uses class


1. Define an empty class

Class Person{};

2. Define a class with member attributes and operations

Class Person{

Member properties.....

Fuck...

}

3. Define a class that cannot be inherited and use the final keyword

Final class Person{

Member properties.....

Fuck...

}

4. Note: The final keyword cannot be used to modify member attributes, but can only modify classes and methods (final methods will be introduced later)

5. Here is a class with final

Define a final class FinalClass, containing a public function

final class FinalClass {

public function ffun() {

echo "This class is final class";

}

}

Define a class ChildFinalClass and inherit the FinalClass class

class ChildFinalClass extends FinalClass {

public function fchildfun() {

echo ‘This class inherits the final class FinalClass’;


}

}

In this way, when executing the above command, the system will prompt


Fatal error: Class ChildFinalClass may not inherit from final class (FinalClass)


Proves that classes defined by the final keyword cannot be inherited by subclasses

2. Definition of member attributes in the class

i. Member attributes are some variable attributes defined for the class. As a class, people have a pair of eyes (normal, except Erlangshen), a mouth, two ears, etc. Fixed proper nouns used to describe or express something are called member attributes

ii. Keywords used in the declaration of member attributes in a class

iii. Common member attribute declarations are composed of the following keywords
It starts with public, var, protected, private, and is followed by a variable. There are also some member attributes including static and constant const.

Public: Represents global, accessible to both internal and external subclasses of the class

Var: In the PHP 5 version, this member attribute will be considered a public type attribute

protected means protected and can only be accessed in this class, subclass or parent class


private
Indicates private and can only be used within this class

Static: 1) Static attributes,

2) Member properties modified with static can be shared by all objects of the same class

3) Static data exists in the data segment in memory when the class is loaded for the first time (initializing the static segment)

4) Use self::member attribute name in the class

                                                                                                                                                                                                         Class name:: Member attribute name

Const: 1) Constant attributes in a class. When declaring constants in a class, you must use const

2) Use SELF :: member attribute name

3) Use outside the class Class name::Member attribute name

Note: The variables in the attributes can be initialized, but the initialized value must be a constant. The constant here refers to the constant that the PHP script is in the compilation stage, not the constant calculated in the running stage after the compilation stage. For example, it cannot contain any operators, cannot be any variables, cannot be a function, etc.

iv. How to call member attributes:

In the member method of the class, you can access the properties and methods of the class through $this->property (property is the property name), but it cannot be used to access the static properties of the class or in the static method. , use self::$property instead. The pseudo variable $this can be used in non-static methods of a class. This pseudo variable is a reference to the instantiated object that calls the method.

Next, use code to explain the above content:

class FinalClass {

//static $a = strTolower();
//This writing is wrong

//const A = 1+2; //This writing is wrong

//public $name = 123+456; 
//This writing is wrong

static $a = '$a';

const A = 'A';

public $name = 'Sister Feng';

protected $sex = 'male+female';

private $age = 23;

}

class ChildFinalClass extends FinalClass{


public function fchildfun(){


echo 'ChildFinalClass::$a->'.ChildFinalClass::$a."


";


Echo 'ChildFinalClass::A->'.ChildFinalClass::A."


";


echo 'Hello everyone, my name is'.$this->name."


";


echo 'I am:'.$this->sex.'生


';


echo 'My year:'.$this->age.'


';

//Since age is a private member attribute, it will not be called here, and it will be prompted that this attribute is not defined in the ChildFinalClass class.

}


}


$obj = new ChildFinalClass();


$obj->fchildfun();

3. Definition of operations in the class

i. I generally like to call operations as member methods. Below I will call operations as methods, but they are all the same

ii. Definition of member methods: Member methods are some function methods defined for the class. For example, take this class as an example. People can eat, run, and type code. These are member methods. That is to say, you can do some executable actions, which we understand as member methods

iii. For access to member methods and member attributes, please refer to the introduction to access to member attributes above.

iv. Member methods and member attributes also include public, protected, private, static, final and the scope is the same. Here are some examples for your reference and understanding.

v. Static member methods can only access static member properties and member methods, and you can use self::static method() to access static methods inside the class, and use class name::static method() to access externally the class


1. Custom method:

class FinalClass {

static $a = '$a';

const A = 'A';

public $name = 'Sister Feng';

protected $sex = 'male+female';

private $age = 23;

//Define a public method

public function publickfun(){


echo 'self::$a->'.self::$a."


"; in the FinalClass class


echo "self::A->".self::A."


"; in FinalClass class


echo 'Hello everyone, my name is:'.$this->name."


";


echo 'I am:'.$this->sex.'生


';


echo 'My year:'.$this->age.'


';

}

//Define a protected method


protected function protectedfun(){


echo 'self::$a->'.self::$a."


"; in the FinalClass class


echo "self::A->".self::A."


"; in FinalClass class


echo 'Hello everyone, my name is:'.$this->name."


";


echo 'I am:'.$this->sex.'生


';


echo 'My year:'.$this->age.'


';


}


//Define a private method

private function privatefun(){

echo 'self::$a->'.self::$a."


";

echo "self::A->".self::A."


"; in FinalClass class

echo 'Hello everyone, my name is:'.$this->name."


";

echo 'I am:'.$this->sex.'生


';

echo 'My year:'.$this->age.'


';


}

}


class ChildFinalClass extends FinalClass{

public function fchildfun(){

echo 'ChildFinalClass::$a->'.ChildFinalClass::$a."


";

Echo 'ChildFinalClass::A->'.ChildFinalClass::A."


";

echo 'I am:'.$this->sex.'生


';

echo 'My year:'.$this->age.'


';

//Since age is a private member attribute, it can be understood that I don’t want others to know my age, so it will not be called here, and it will prompt that this attribute is not defined in the ChildFinalClass class.

$this->publickfun();

$this->protectedfun();

$this->privatefun();   

//Since privatefun is a private member method, it will not be called here.


}

}


$obj = new ChildFinalClass();


$obj->fchildfun();


2.Magic method

i. Magic methods must be defined as public, as must all other magic methods

ii. From PHP 5 and later, classes in PHP can use magic methods. It stipulates that methods starting with two underscores (__) are reserved as magic methods, so it is recommended that everyone’s function names should not start with __, unless it is to overload existing magic methods. Here are some magic methods. If If you want to know more about it, you can inquire about a certain one, so I won’t introduce it in detail here.

1. __construct() construction method


__destruct()

Destruction method

2. __clone()

If you want to copy an object, you need to use the clone method

3.__toString()

The

method is automatically called when converting an object into a string, such as when using echo to print the object

4. __sleep() is used when serializing


__wakeup is called during deserialization

5. __set_state()

This static method will be called when var_export() is called (valid since PHP 5.1.0)

6. __invoke (valid for PHP 5.3.0 or above)
When trying to invoke an object as a function, the __invoke method is automatically called.

7. __callStatic (valid for PHP 5.3.0 and above) is to handle static method calls

8. __get() When an undefined attribute is called, this method will be triggered, and the parameter passed is the name of the attribute being accessed.


__set() This method will be triggered when assigning a value to an undefined attribute. The parameters passed are the attribute name and value to be set. The non-declaration here includes attributes whose access control is protected and private (that is, attributes that do not have permission to access) when called using an object.

9. __isset() This method is called when the isset() function is called on an undefined attribute


__unset() This method is called when the unset() function is called on an undefined property

10. __call( $method, $arg_array )
This method is called when calling an undefined method

The undefined methods here include methods that do not have permission to access; if the method does not exist, go to the parent class to find the method. If it does not exist in the parent class, call the __call() method of this class. If the __call() method does not exist in this class, go to the __call() method in the parent class.

11. __autoload() automatic loading magic method

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/732963.htmlTechArticleThe concept of class: A class is a collection of objects with the same properties and operations. It provides a unified abstract description for all objects belonging to this class, which includes two main attributes and operations...
Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.