国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial Detailed explanation of commonly used keywords and magic methods in PHP object-oriented

Detailed explanation of commonly used keywords and magic methods in PHP object-oriented

Jul 10, 2017 am 11:46 AM
php Keywords use

1.construct()

The instantiated object is automatically called. Construct is called when construct and the function with the class name and function name exist at the same time, and the other one is not called.

The function with the class name and function name is the old version of the constructor.

2.destruct()

is called when deleting an object or when an object operation ends.

3.call()

The object calls a method. If the method does not exist, call this method

4.get()

Read an object property. If the object property is private, it will be called

5. set()

When assigning a value to an object property, it will be called if the property is private

6.toString()

It will be called when printing an object.

7.clone()

Called when cloning an object, such as: $a=new test(); $a1=clone $a;

8.sleep( )

Serialize was called before. If the object is larger than and you want to delete something during serialization, you can use it.

9.wakeup()

is called when Unserialize is used to do some object initialization work.

10.isset()

Detects whether an object's attributes exist. If the detected attribute is private, it will be called.

11.unset()

When deleting an object attribute, if the deleted object attribute is private, it will be called

12.set_state()

Called when var_export is called. Use the return value of set_state as the return value of var_export.

13.autoload()

When instantiating an object, if the corresponding class does not exist, this method will be used.


The following editor will bring you a detailed discussion of PHP object-orientedcommonly used keywords and magic methods. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Commonly used keywords in PHP object-oriented

final

1.Final cannot modify member attributes (this keyword is not used for constants in classes)

2.Final can only modify classes and methods

Function:

Classes modified with final cannot be inherited by subclasses

Methods modified with final cannot be overridden by subclasses

Used to restrict classes from being inherited, methods If not overridden, use final

<?php
//final修飾的類不能被繼承
final class Person{
  var $name;
  var $age;
  var $sex;

  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function fun1(){
    echo $this->name;
  }
}

//Student類繼承類用final修飾的Person類,所以會(huì)報(bào)錯(cuò)
class Student extends Person{
}

$stu=new Student("zs",20,"nan");

$stu->fun1();
?>

static (static keyword)

1. Use static to modify member properties and member methods, but not Modified class

2. Member attributes modified with static can be shared by all objects of the same class

3. Static data is stored in the data segment in memory (initializing the static segment)

4. Static data is allocated to memory when the class is loaded for the first time. When the class is used in the future, it is obtained directly from the data segment

5. What is a class being loaded? As long as this class is used in the program (this class name appears)

6. Static methods (static modified methods) cannot access non-static members (static members can be accessed in non-static methods)

Because non-static members must be accessed using objects, $this is used to access internal members. Static methods do not need to be called using objects, so there is no object. $this cannot represent objects. Non-static Members must also use objects

If you are sure that non-static members are not used in a method, you can declare this method as a static method

Note: Static members must use class names To access, don’tCreate an object, don’t use an object to access

Class name::static member

If you use static members in a class, you can use self to represent this class

const

1. It can only modify member attributes

2. Use const

# to declare constant attributes in a class ##3. The access method is the same as static member properties (use class name::constant outside the class and self::constant inside the class)

4. Constants must be given initial values ??when they are declared.

<?php
//定義一個(gè)類“人們”
class Person{
  protected $name;
  protected $age;
  protected $sex;
  static $country="中國";
  //聲明一個(gè)常量
  const RUN="走";

  //構(gòu)造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function getCountry(){
    //如果在類中使用靜態(tài)成員,可以使用self代表本類
    return self::$country;
  }

  function say(){
    echo "我的名字:{$this->name},我的年齡:{$this->age},我的性別:{$this->sex}。<br>";
  }

  protected function eat(){
    echo "吃飯!<br>";
  }

  function run(){
    //在類的內(nèi)部使用常量 self::常量
    echo self::RUN."<br>";
  }

  //聲明靜態(tài)的方法
  static function hello(){
    echo "你好<br>";
  }
}

Magic methods commonly used in PHP object-oriented

call()

Function: When calling a method that does not exist in the object, a system error will appear, and then the program will exit.

When to call automatically: It will be called automatically when calling a method that does not exist in an object

Handle some non-existent error calls

This method requires two Parameters

<?php
//定義一個(gè)類“人們”
class Person{
  protected $name;
  protected $age;
  protected $sex;
  static $country="中國";
  //聲明一個(gè)常量
  const RUN="走";

  //構(gòu)造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function getCountry(){
    //如果在類中使用靜態(tài)成員,可以使用self代表本類
    return self::$country;
  }

  function say(){
    echo "我的名字:{$this->name},我的年齡:{$this->age},我的性別:{$this->sex}。<br>";
  }

  protected function eat(){
    echo "吃飯!<br>";
  }

  function run(){
    //在類的內(nèi)部使用常量 self::常量
    echo self::RUN."<br>";
  }

  //處理一些不存在的錯(cuò)誤調(diào)用
  //就會(huì)在調(diào)用一個(gè)對(duì)象中不存在的方法時(shí)就會(huì)自動(dòng)調(diào)用
  function call($methodName,$args){
    //$methodName調(diào)用不存在方法的方法名 $args里面的參數(shù)
    echo "你調(diào)用的方法{$methodName}(參數(shù):";
    print_r($args);
    echo ")不存在<br>";
  }

  //聲明靜態(tài)的方法
  static function hello(){
    echo "你好<br>";
  }
}

$p=new Person("張三",20,"女");

$p->test(10,20,30);
$p->demo("aa","bb");
$p->say();
?>

toString()

is automatically called when directly outputting an object reference. It is the fastest way to quickly obtain a string representation. Method

<?php
//定義一個(gè)類“人們”
class Person{
  protected $name;
  protected $age;
  protected $sex;
  static $country="中國";
  //聲明一個(gè)常量
  const RUN="走";

  //構(gòu)造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function say(){
    echo "我的名字:{$this->name},我的年齡:{$this->age},我的性別:{$this->sex}。<br>";
  }

  function toString(){
    return self::$country."<br>{$this->name}<br>{$this->age}<br>{$this->sex}<br>".self::RUN;
  }
}

$p=new Person("張三",21,"女");
echo $p;
?>

clone()

Clone object is processed using clone()

Original (original object)

Copy (copied object)

clone() is a method automatically called when cloning an object

As soon as an object is created, there must be an initialization action, and The constructor method constuct has similar functions

在clone()方法中的$this關(guān)鍵字代表的是復(fù)本的對(duì)象,$that代表原本對(duì)象

<?php
//定義一個(gè)類“人們”
class Person{
  var $name;
  protected $age;
  protected $sex;
  static $country="中國";
  //聲明一個(gè)常量
  const RUN="走";

  //構(gòu)造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function say(){
    echo "我的名字:{$this->name},我的年齡:{$this->age},我的性別:{$this->sex}。<br>";
  }

  function clone(){
    $this->name="王五";
    $this->age=18;
    $this->sex="男";
  }

  function destruct(){
    echo $this->name."<br>";
  }
}

$p=new Person("張三",21,"女");
$p->say();
//這并不能叫做克隆對(duì)象,因?yàn)樵谖鰳?gòu)時(shí)只析構(gòu)一次
/*$p1=$p;
$p1->name="李四";
$p1->say();*/

$p1= clone $p;
$p1->say();
?>

autoload()

注意:其它的魔術(shù)方法都是在類中添加起作用,這是唯一一個(gè)不在類中添加的方法

只要在頁面中使用到一個(gè)類,只要用到類名,就會(huì)自動(dòng)將這個(gè)類名傳給這個(gè)參數(shù)

<?php
function autoload($className){
  include "./test/".$className.".class.php";
}

  $o=new One;
  $o->fun1();  

  $t=new Two;
  $t->fun2();

  $h=new Three;
  $h->fun3();

?>

test里的文件

one.class.php

<?php
class One{
  function fun1(){
    echo "The Class One<br>";
  }
}
?>

two.class.php

<?php
class Two{
  function fun2(){
    echo "The Class Two<br>";
  }
}
?>

three.class.php

<?php
class Three{
  function fun3(){
    echo "The Class Three<br>";
  }
}
?>

對(duì)象串行化(序列化):將一個(gè)對(duì)象轉(zhuǎn)為二進(jìn)制串(對(duì)象是存儲(chǔ)在內(nèi)存中的,容易釋放)

使用時(shí)間:

1.將對(duì)象長時(shí)間存儲(chǔ)在數(shù)據(jù)庫或文件中時(shí)

2.將對(duì)象在多個(gè)PHP文件中傳輸時(shí)

serialize(); 參數(shù)是一個(gè)對(duì)象,返回來的就是串行化后的二進(jìn)制串

unserialize(); 參數(shù)就是對(duì)象的二進(jìn)制串,返回來的就是新生成的對(duì)象

sleep()

是在序列化時(shí)調(diào)用的方法

作用:就是可以將一個(gè)對(duì)象部分串行化

只要這個(gè)方法中返回一個(gè)數(shù)組,數(shù)組中有幾個(gè)成員屬性就序列化幾個(gè)成員屬性,如果不加這個(gè)方法,則所有成員都被序列化

wakeup()

是在反序列化時(shí)調(diào)用的方法

也是對(duì)象重新誕生的過程

<?php
//定義一個(gè)類“人們”
class Person{
  var $name;
  protected $age;
  protected $sex;
  static $country="中國";
  //聲明一個(gè)常量
  const RUN="走";

  //構(gòu)造方法
  function construct($name,$age,$sex){
    $this->name=$name;
    $this->age=$age;
    $this->sex=$sex;
  }

  function say(){
    echo "我的名字:{$this->name},我的年齡:{$this->age},我的性別:{$this->sex}。<br>";
  }

  function clone(){
    $this->name="王五";
    $this->age=18;
    $this->sex="男";
  }

  //是在序列化時(shí)調(diào)用的方法,可以部分串行化對(duì)象
  function sleep(){
    return array("name","age");
  }

  //是在反序列化時(shí)調(diào)用的方法,也是對(duì)象重新誕生的過程??梢愿淖兝锩娴闹?
  function wakeup(){
    $this->name="sanzhang";
    $this->age=$this->age+1;
  }

  function destruct(){

  }
}
?>

read.php

<?php
  require "11.php";
  
  $str=file_get_contents("mess.txt");
  $p=unserialize($str);

  echo $p->say();
?>

write.php

<?php
  require "11.php";

  $p=new Person("張三",18,"男");

  $str=serialize($p);

  file_put_contents("mess.txt",$str);
?>

The above is the detailed content of Detailed explanation of commonly used keywords and magic methods in PHP object-oriented. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the current session ID in PHP? How to get the current session ID in PHP? Jul 13, 2025 am 03:02 AM

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

PHP get substring from a string PHP get substring from a string Jul 13, 2025 am 02:59 AM

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

How do you perform unit testing for php code? How do you perform unit testing for php code? Jul 13, 2025 am 02:54 AM

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

How to split a string into an array in PHP How to split a string into an array in PHP Jul 13, 2025 am 02:59 AM

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

How does PHP handle Environment Variables? How does PHP handle Environment Variables? Jul 14, 2025 am 03:01 AM

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

How to pass a session variable to another page in PHP? How to pass a session variable to another page in PHP? Jul 13, 2025 am 02:39 AM

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

See all articles