Blogger Information
Blog 11
fans 0
comment 1
visits 7831
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0202面向对象编程基础
一代宗师
Original
546 people have browsed it

# 类声明,类的实例化

<?php

// class 声明一个类
class student{
//类属性
public $name = ‘张三’;
public $age = 20;
//构造方法初始化 $name和$age变量
function __construct($name,$age){

  1. $this -> name = $name;
  2. $this -> age = $age;
  3. }
  4. public function mingzi()
  5. {
  6. return $this->name;
  7. }

}
// new:类实例化
$obj = new student(‘李四’,28);
var_dump($obj);

类的静态成员

<?php
//静态成员
//static 声明静态成员

class user{

  1. public static $name="小花";
  2. public static $sex="女";
  3. // public function __construct($name="张三",$sex="男"){
  4. // self::$name = $name;
  5. // self::$sex = $sex;
  6. // }
  7. public static function mingzi(){
  8. //调用静态成员用类名::静态成员
  9. return '我叫'.self::$name.'我是'.self::$sex;
  10. }

}
// $yuangong=new user();
// var_dump(user::$name);
echo user::mingzi();

类的扩展

<?php
//类的扩展

class phone{
protected $name = ‘座机’;
protected $gn= ‘打电话’;

  1. public function chi()
  2. {
  3. return "$this->name , $this->gn";
  4. }

}

$elephant = new phone();
echo $elephant->chi();

class mobile extends phone {

  1. private $yinyue = '音乐';
  2. private $shipin = '视频';
  3. public function zhineng(){
  4. return "我不仅会 $this->gn ,我还会 $this->yinyue , $this->shipin";
  5. }

}

$gongju = new mobile();
echo $gongju->zhineng();

trait功能

<?php
//通过在类中使用use 关键字,声明要组合的Trait名称,具体的Trait的声明使用Trait关键词,Trait不能实例化
trait dome1{
public $name = ‘老王’;

  1. public function text(){
  2. return $this->name;
  3. }

}

class dome2{
use dome1;
}

$dome2 = new dome2();
echo $dome2->text();

trait 的冲突与优先级的解决方案

1.优先级解决
2.别名

<?php
trait student{
public function zhangsan(){
return ‘我是张三’;
}
}

trait student2{
public function zhangsan(){
return ‘我也是张三’;
}
}

class student3{

use student,student2{
//优先级
student::zhangsan insteadOf student2;
//别名
student2::zhangsan as T2zhangsan;
}
}

$student3 = new student3();
echo $student3->zhangsan().’<br>‘;
echo $student3->T2zhangsan();

trait与父类的区别与联系

子类>trait>父类
输出子类chi()

没有子类输出trait的chi()

都没有则输出父类的chi();

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post