<?php
//类声明,类的实例化
class Introduce
{
protected $name;
protected $age;
public function __construct($name,$age)
{
$this->name=$name;
$this->age=$age;
}
public function m1():string
{
return "我叫$this->name ,我今年$this->age 岁";
}
}
$introduce=new Introduce('小红',20);
echo $introduce->m1(),'<br>';
//类的静态成员与类的扩展
class Introduce1 extends Introduce
{
protected static $gender;
public function __construct($name,$age,$gender)
{
parent::__construct($name,$age);
self::$gender=$gender;
}
public function m2()
{
return parent::m1().",性别是:".self::$gender;
}
}
$introduce1=new Introduce1('小红',20,'女');
echo $introduce1->m2();
<?php
<?php
//trait的功能
trait A1
{
public function m1($a,$b)
{
return $a*$b;
}
}
class B1
{
use A1;
}
class B2
{
use A1;
}
echo (new B1)->m1(6,2),'<br>';
// trait与父类的区别与联系
class C
{
public $name;
public $age;
public function __construct($name,$age)
{
$this->name=$name;
$this->age=$age;
}
public function m1()
{
return "我叫 $this->name , 今年 $this->age 岁了";
}
}
trait B
{
public function m2($a,$b)
{
return $a*$b;
}
}
class D extends C
{
use B;
}
$d=new D('小马',20);
//trait里面有类的方法,但是没有类的实例,不能实例化,只能存储一些轻量级的类方法
echo $d->m1(),'<br>';
echo '2X2='.$d->m2(2,2);
<?php
<?php
//解决trait的冲突,1,设置优先级,2.给另一个起个其他的名字
trait T1
{
public function m1($a,$b)
{
return $a*$b;
}
}
trait T2
{
public function m1($a,$b)
{
return $a+$b;
}
}
class B
{
use T1, T2{
//1.设计优先级
T1::m1 insteadOf T2;
// 2.别名
T2::m1 as T2m1;
}
}
echo (new B)->m1(5,2),'<br>';
echo (new B)->T2m1(2,2),'<br>';