search
Homephp教程PHP源码php类的魔术方法

在php 5中,提供了构造函数,析构函数,对象克隆的方法,重载方法等,

<script>ec(2);</script>

1、构造函数__construct

如果在类申明中__construct函数,将被当成一个构造函数并且在对象建立时被执行,但在php4中,构造函数的名称与类名相同就是构造函数哦,这一点有一些不同。

2、析构函数__destruct

如果在php类中申明了,在对象被销毁时调用__destruct函数

下面来看个实例

 代码如下 复制代码
class Session
{
    public  function __construct()
{
     echo '构造函数执行';
    }
    public  function __destruct()
    {
      echo '析构函数执行';
    }
}
$Obj = new Session;
unset($Obj);//删除对象, __destruct()会被调用的
//输出
//构造函数执行
/析构函数执行
?>

上面在使用new创建对象时就执行了__construct,对象结束时就执行了__destruct()

3、__clone()克隆函数

 代码如下 复制代码

class Session
{
 public $age = 20;
 public $sub = null;
 public function __clone()
 {
  $this->sub=clone $this->sub;
 }
}
class Session 2
{
 public $value=5;
}
$s   = new Session;
$s->sub=new Session 2;
$s2 = clone $s;
$s->sub->$value =10;
echo $s2->sub->$value;
?>

4  现在来看关于重载函数__get ,__set,__call函数

 代码如下 复制代码

class Session
{
 protected function __call($func,$para)
 {
  echo '方法不存在:’func." ".'参数为:'." ";
  print_r($para);
 }
}
$s=new Session ();
echo $c->getNames('hello','you');
/*
输出:
方法不存在:getNames
参数为:
Array
(
    [0] => hello
    [1] => you
)
*/
?>

申明本站原创文章转载注明来源于www.111cn.net

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft