当前位置:网站首页>PHP classes and objects
PHP classes and objects
2022-04-23 15:35:00 【Jimeng network worry free】
Basic concepts
attribute
Class constant
Object inheritance
Automatically load objects
Constructors and destructors
Access control
Range resolution operator (::)
Static keyword
abstract class
Interface
Basic concepts
Definition
- Each class is defined with the keyword class start , Followed by the class name ( Non reserved words ).
- The class name is followed by a pair of curly braces , It contains the definitions of class properties and methods .
<?php
class A
{
// attribute
public $a;
private $b;
// Method
public function actionA()
{
}
}
Class member defaults
When defining class properties , You can use the default values
<?php
class A
{
// The default value is
public $a = 'Hi';
private $b = 'Hello';
// Method
public function actionA()
{
}
}
Create examples
To create an instance of an object , Use keywords new
<?php
$a = new A();// Create a class A Example
Object Assignment
When assigning an instance of an object that has been created to a new variable , The new variable will access the same instance , It's the same as assigning values to this object . This behavior is the same as when passing an instance to a function . You can use cloning to create a new instance of a created object .
<?php
class A
{
}
$a = new A();
$b = $a;
$c = &$a;
$d = clone $a;
$a = null;
var_dump($a,$b,$c,$d);
The result is
NULL
object(A)#1 (0) {
}
NULL
object(A)#2 (0) {
}
$this
Pseudo variable t h i s can With stay When One individual Fang Law stay Yes like Inside Ministry transfer use when send use . this Can be used when a method is called inside an object . this can With stay When One individual Fang Law stay Yes like Inside Ministry transfer use when send use .this Is a call object ( It is usually the object to which the method belongs , But it can also be another object , If the method is called statically from within the second object ) References to .
edit /home/project/this.php
<?php
class A
{
function actionA()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo '$this is not defined.'.PHP_EOL;
}
}
}
class B
{
function actionB()
{
A::actionA();
}
}
$a = new A();
$a->actionA();
A::actionA();
$b = new B();
$b->actionB();
B::actionB();
perform
php this.php
It can be seen from the results ,$this Can only be used in objects , Middle note cannot be invoked in static method. . But if you're on another object ( class B) The static method is called , be $this Point to this class ( B ).
Object inheritance
A class can be used in a declaration extends Keyword inherits methods and members of another class .PHP Multiple inheritance is not supported , A class can only inherit one class .
class A
{
}
class B extends A
{
}
Inherited methods and members can be overridden by redeclare with the same name , Unless the method is defined by the parent class final keyword . Can pass parent:: To access the overridden method or member .
edit /home/project/extends.php
<?php
class A
{
public function sayHi()
{
echo "Hi".PHP_EOL;
}
final public function sayBye()
{
echo "Bye".PHP_EOL;
}
}
class B extends A
{
public function sayHi()
{
parent::sayHi();
echo "Hello".PHP_EOL;
parent::sayBye();
}
// Can't be covered , Report errors , When practicing, pay attention to delete this method
public function sayBye()
{
echo "See you";
}
}
$b = new B();
$b->sayHi();
perform
php extends.php
As you can see from the results
- Use final The decorated method cannot be covered
- Use parent:: You can call a parent method or property
attribute
Definition
The variable members of a class are called properties . Attribute declarations are defined by access control keywords public,protected or private And a variable , At the same time, the default value can be added .
<?php
class A
{
// Can only be used on the class itself
private $a = "Hello";
// Can be used in subclasses and classes themselves
protected $b = <<<EOT This is variable b; EOT;
// Except subclasses , Class itself , It can also be accessed from the outside
public $c;
}
Access properties
In the member method of a class , Can pass $this-> Add variable names to access class properties and methods , Use static properties or static methods self:: Add variable name .
Be careful self:: The variable name after this method needs to be added $ Symbol , and $this-> The variable name after does not need to be added
edit /home/project/property.php
<?php
class A
{
private $a = "Hello";
protected $b = <<<EOT This is property b EOT;
public static $c = 'This is a'.' static property';
public function talk()
{
echo $this->a.PHP_EOL;
echo $this->b.PHP_EOL;
echo self::$c;
}
}
(new A())->talk();
perform
php property.php
Class constant
We can define constants in classes . The value of the constant will always remain the same . You don't need to use... When defining and using constants $ Symbol .
<?php
class A
{
const ENV = 'env';
const HELLO = 'Hello';
}
Interface (interface) Constants can also be defined in
<?php
interface B
{
const ENV = 'ENV';
public function sayHi();
}
Automatically load objects
To perform a class operation , You need to load this class first , for example include,require etc. .
If there are many classes to execute , You need a lot include operation , It will cause repeated loading , A series of problems such as management suffering .
stay PHP 5 in , Don't do that , have access to spl_autoload_register() Function to register any number of autoloaders .
<?php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
new A();
new B();
This example attempts to start from A.php and B.php File loading A and B class , amount to
<?php
include 'A.php';
include 'B.php';
new A();
new B();
Constructors and destructors
Constructors
void __constuct()
When creating an object ( new operation ), The constructor will automatically call
class A
{
public function __construct()
{
echo 'init...'.PHP_EOL;
}
public function sayHi()
{
echo "hi";
}
}
(new A())->sayHi();
The output is
init…
hi
Instantiation A Execute constructor when .
Be careful : If a constructor is defined in a subclass, the constructor of its parent class is not implicitly called . The constructor to execute the parent class , Need to be called in the constructor of the subclass. parent::__construct().
<?php
class A
{
public function __construct()
{
echo "A";
}
}
class B extends A
{
public function __construct()
{
parent::__construct();
echo "B";
}
}
new A(); // A
new B(); // AB
Destructor
void __destruct(void)
Destructors execute when all references to an object are deleted or when the object is explicitly destroyed .
<?php
class A {
public function __construct() {
echo 'Start...';
}
public function sayHi()
{
echo "Hi...";
}
public function __destruct() {
echo "Finish";
}
}
(new A())->sayHi(); // Start...Hi...Finish
Like constructors , The destructor of the parent class is not secretly invoked by the engine. . The destructor to execute the parent class , Must be explicitly called in the destructor body of a subclass parent::__destruct().
Destructors even in use exit() The termination script is also called when it runs . In destructors call exit() The rest of the shutdown operation will be aborted .
Access control
Access control over properties or methods , It's by adding keywords in front of it public
、protected
or private
To achieve . If you don't add , The default is public
.
public
Defined class members can be accessed anywhere
protected
The defined class members can be accessed by the subclasses and superclasses of their classes ( Of course , The class of the member can also access )
private
Defined class members can only be accessed by their class
edit /home/project/access.php
<?php
class A
{
private $hi = 'Hi'.PHP_EOL;
protected $hello = 'Hello'.PHP_EOL;
public $bye = 'Bye'.PHP_EOL;
private function sayHi()
{
echo $this->hi;
}
protected function sayHello()
{
echo $this->hello;
}
public function sayBye()
{
echo $this->bye;
}
}
class B extends A
{
public function talk()
{
parent::sayHello();
}
}
$a = new A();
$a->sayHi();// Report errors , Unable to call
$b = new B();
$b->sayHello();// Report errors , Unable to call
$b->talk();
$b->sayBye();
perform
php access.php
From the results, we can see , Declare as private Methods or properties of cannot be called outside a class , At the same time, subclasses cannot call this method .
Range resolution operator (::)
Range resolution operator , It can be simply a pair of colons , Can be used to access static members 、 Methods and constants , It can also be used to override members and methods in classes .
When accessing these static members outside the class 、 Methods and constants , You must use the name of the class .
edit /home/project/paamayim.php
<?php
class A
{
const CONST_A = 'A constant value';
public static function sayHello()
{
echo 'Hello';
}
}
class B extends A
{
public static $b = 'static var b';
/** * Override the parent method * */
public static function sayHello()
{
echo parent::sayHello().' World'.PHP_EOL;
}
public static function actionB()
{
self::sayHello();
echo parent::CONST_A.PHP_EOL;
echo self::$b;
}
}
B::actionB();
perform
php paamayim.php
From the results, we can see
- Use
parent,self
You can call the parent class and its own method properties ::
You can call static methods , Static properties and constants
Static keyword
Declare a class member or method as static, You can directly access without instantiating a class . Static members cannot be accessed through an object ( Except for static methods ).
Because static methods don't need to be called through objects , So pseudo variables $this Not available in static methods . Static properties cannot be passed by objects -> Operator to access .
Be careful : stay PHP7 Pass through (::) Calling a non static method produces a E_DEPRECATED Level warning , Do not approve of such use , Support for this usage may be removed in the future .
edit /home/project/static.php
<?php
class Test
{
public $hi = 'Hi';
public static $hello = 'Hello';
public function sayHi()
{
echo $this->hi;
}
public static function sayHello()
{
echo self::$hello;
}
public function sayWorld()
{
echo " World".PHP_EOL;
}
}
$obj = new Test();
$obj->sayHi();
$obj->sayWorld();
Test::sayHello();
Test::sayWorld();
perform
php static.php
It can be seen from the results
- adopt :: You can execute static and non static methods , But I don't approve of calling non static methods in this way , This method may be officially removed , So above sayWorld(), It should be through (new Test())->sayWorld() Call... In this way
- Static properties and methods can be self Key word call
Like everything else PHP Same as static variables , Static properties can only be initialized to a character value or a constant , You can't use expressions . So you can initialize static properties as integers or arrays , But it cannot point to another variable or function return value , Nor can it point to an object .
abstract class
Defined as Abstract classes may not be instantiated directly
, Any class , If at least one of its methods is declared abstract , Then the class must be declared abstract . If class methods are declared abstract , Then it can't include the specific function realization .
edit /home/project/abstract.php
<?php
abstract class Say
{
abstract public function sayHello($word);
abstract public function sayHi();
}
class Speak extends Say
{
public function sayHello($word)
{
echo "Hello $word";
}
public function sayHi()
{
echo "Hi".PHP_EOL;
}
}
$s = new Speak();
$s->sayHi();
$s->sayHello("World");
perform
php abstract.php
It can be seen from the results
- When inheriting an abstract class , A subclass must define all abstract methods in the parent class . for example , In the class Speak Remove method from sayHi(), The result is
Fatal error: Class Speak contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Say::sayHi)...
- The access control of these methods must be the same as in the parent class ( Or more relaxed ). for example , In the class Speak in sayHi() Declare as protected, False report
Fatal error: Access level to Speak::sayHi() must be public (as in class Say)...
- In addition, the way the method is called must match , That is, the type and the number of required parameters must be the same . for example , Remove abstract method sayHello() Parameters in , be
Fatal error: Declaration of Speak::sayHello($word) must be compatible with Say::sayHello()...
Interface
Use interface (interface), You can specify which methods a class must implement , But you don't need to define the details of these methods . We can go through interface To define an interface , It's like defining a standard class , But all the methods defined in it are empty . All methods defined in the interface must be public, This is a feature of the interface .
Realization
To implement an interface , have access to implements The operator . Class must implement all the methods defined in the interface , Otherwise, I will report one fatal error . If you want to implement multiple interfaces , You can use commas to separate the names of multiple interfaces .
<?php
interface A
{
public function actionA();
}
interface B
{
public function actionB();
}
// Implement multiple interfaces
class C implements A, B
{
public function actionA()
{
//do something
}
public function actionB()
{
//do something
}
}
Be careful :
- When implementing multiple interfaces , Methods in an interface cannot have duplicate names .
- Interfaces can also inherit , By using extends The operator .
<?php
interface A
{
public function actionA();
}
interface B extends A
{
public function actionB();
}
class C implements A
{
public function actionA()
{
//do something
}
public function actionB()
{
//do something
}
}
Constant
Constants can also be defined in the interface . Interface constants and class constants are used exactly the same . They are all fixed values , Cannot be modified by subclasses or subinterfaces .
<?php
interface A
{
const B = 'Interface constant';
}
// Output interface constant
echo A::B;
// Wrong writing , Because the value of a constant cannot be modified . The concept of interface constant is the same as that of class constant .
class C implements A
{
const B = 'Class constant';
}
An anonymous class
php7 Supported by new class To instantiate an anonymous class , This can be used to replace some “ Burn immediately after use ” The complete class definition of .
<?php
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
echo $msg;
}
});
var_dump($app->getLogger());
?>
The above routine will output :
object(class@anonymous)#2 (0) {
}
版权声明
本文为[Jimeng network worry free]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231526352446.html
边栏推荐
- 使用 Bitnami PostgreSQL Docker 镜像快速设置流复制集群
- What exactly does the distributed core principle analysis that fascinates Alibaba P8? I was surprised after reading it
- Kubernetes详解(九)——资源配置清单创建Pod实战
- Node. JS ODBC connection PostgreSQL
- Independent operation smart farm Innovation Forum
- 函数(第一部分)
- 基础贪心总结
- Baidu written test 2022.4.12 + programming topic: simple integer problem
- [backtrader source code analysis 18] Yahoo Py code comments and analysis (boring, interested in the code, you can refer to)
- Detailed explanation of kubernetes (IX) -- actual combat of creating pod with resource allocation list
猜你喜欢
机器学习——逻辑回归
Today's sleep quality record 76 points
JVM-第2章-类加载子系统(Class Loader Subsystem)
木木一路走好呀
What exactly does the distributed core principle analysis that fascinates Alibaba P8? I was surprised after reading it
Mysql database explanation (VII)
MultiTimer v2 重构版本 | 一款可无限扩展的软件定时器
Detailed explanation of kubernetes (IX) -- actual combat of creating pod with resource allocation list
KNN, kmeans and GMM
导入地址表分析(根据库文件名求出:导入函数数量、函数序号、函数名称)
随机推荐
通過 PDO ODBC 將 PHP 連接到 MySQL
T2 iCloud日历无法同步
移动app软件测试工具有哪些?第三方软件测评小编分享
字节面试 transformer相关问题 整理复盘
Modify the default listening IP of firebase emulators
What role does the software performance test report play? How much is the third-party test report charged?
Squid agent
山寨版归并【上】
SSH connects to the remote host through the springboard machine
KNN, kmeans and GMM
The wechat applet optimizes the native request through the promise of ES6
JSON date time date format
Special analysis of China's digital technology in 2022
WPS品牌再升级专注国内,另两款国产软件低调出国门,却遭禁令
Deep learning - Super parameter setting
Common types of automated testing framework ▏ automated testing is handed over to software evaluation institutions
Common interview questions of operating system:
Sword finger offer (1) -- for Huawei
How did the computer reinstall the system? The display has no signal
Mysql database explanation (8)