面向对象构造方法

构造方法

构造方法:__construct()
php自带的类方法,是指在new对象时,自动触发的方法 就像婴儿刚出来就会哭,不用叫,也不用调用

1  class Human{
2    public function __construct(){
3    echo '555555';
4    }}$baby = new Human();

利用此方法可以完成一些初始化⼯作。
做一些初始化的工作

 1  //定义一个人类
 2  
 3  class Person{
 4  public $name;
 5  public $age=18;
 6  public $sex;
 7  public function say(){
 8  echo '我是:'.$this->name.'今年:'.$this->age.'岁,我是欧个'.$this-
 9 >sex;
10  }
11  //初始化的方法
12  //如果我们的初始化方法里面给了默认值 那么定义属性的默认值没有意义了
13  public function __construct($name,$age=19,$sex='淫妖'){
14  $this->name = $name;
15  $this->age = $age;
16  $this->sex = $sex;
17  }
18 
19  //构造方法的另一种表示方法,方法名跟类名相同,也叫构造方法,是以前的写法
20  //public function Person($name,$age=19,$sex='淫妖'){
21  // $this->name = $name;
22  // $this->age = $age;
23  // $this->sex = $sex;
24  //}
25  }
26  $dl = new Person('武大郎');
27  $dl->say();
28  echo '<hr/>';
29  $xm = new Person('西门');
30  //初始化
31  // $xm ->name = '西门';
32  // $xm->age = 20;
33  // $xm->sex = '战神';
34  //$xm->init('西门);
35  $xm->say();

如果同时存在两个构造方法会怎么样?

<?php
  class Person{
  public $name;
  //最新的构方法会有效
  public function __construct($name){
  $this->name=$name;
  } //传统的构造方法
  //在使用new关键字得到对象的时候自动调用
  public function Person($name){
  $this->name=$name.'###########';
    } 
}

 $p = new Person('jack'); var_dump($p);

如果同时存在新旧两种构造方法,以最新的construct写法为输出

猜你喜欢

转载自www.cnblogs.com/zhony/p/10241097.html