php代码
程序员文章站
2022-07-04 21:18:36
...
1.
<?php
class Person
{
const COUNT = 10;
}
$p = 'Person';
echo $p::COUNT;//10 通过变量,调用类中的属性
echo '<br/>';//PHP_EOL并没有显示换行效果
echo Person::COUNT;//10
2.
/**
* 普通成员,只能由对象调用
* 静态方法,对象和类皆可调用
* 静态属性,只能由类调用
*/
class Person
{
public static $age = 20;
public $sex = 1;
function eat()
{
return self::$age;
}
static function say()
{
return self::$age;
}
}
echo Person::eat();//Deprecated报错 同时输出结果 20
echo '<br/>';
$p = new Person;
echo $p->eat();//20
echo '<br/>';
echo $p->say();//20
echo '<br/>';
echo Person::say();//20
echo '<br/>';
//echo Person::$sex;//Error
echo '<br/>';
echo $p->sex;//1
echo '<br/>';
echo Person::$age;//20
echo '<br/>';
echo $p->age;//Notice报错
3.
/**
* 接口的常量不能被子类或子接口覆盖
* 类的常量可以
*/
class Person
{
const AGE = 28;
}
class Male extends Person
{
const AGE = 29;
}
echo Person::AGE;//28
echo '<br />';
echo Male::AGE;//29
interface Product
{
const PRICE = 100;
}
interface Bike extends Product
{
const PRICE = 200;
}
class MountainBike implements Product
{
const PRICE = 300;
}
class PhoenixBike implements Bike
{
}
//echo MountainBike::PRICE;//FATAL
echo PhoenixBike::PRICE;//FATAL
4.
/**
* 两个trait在同一个类中存在重名方法时,解决冲突的方式
*/
trait A
{
function one()
{
return 'A';
}
}
trait B
{
function one()
{
return __CLASS__;
}
}
class C
{
use A,B {
A::one insteadOf B;
B::one as two;
}
}
$c = new C;
echo $c->one();//A
echo '<br/>';
echo $c->two();//C
5.
/**
* 修改trait方法的访问权限
*/
trait A
{
function one()
{
return __CLASS__;
}
}
class B
{
use A;
}
class C
{
use A {
one as private two;
}
}
$b = new B;
echo $b->one();//B
echo '<br/>';
$c = new C;
echo $c->one();//C
echo $c->two();//Error
6.
/**
* 静态变量
*/
trait A
{
function inc()
{
static $o = 0;
$o++;
echo "$o<br/>";
}
}
class B
{
use A;
}
class C
{
use A;
}
$b = new B;
$b->inc();//1
$b->inc();//2
$b2 = new B;
$b2->inc();//3
$c = new C;
$c->inc();//1
7.
/**
* 匿名类
*/
class A
{
private $pri = 2;
protected $pro = 3;
protected function func()
{
return 4;
}
public function func2()
{
return new class($this->pri) extends A
{
private $pri2;
function __construct($prop)
{
$this->pri2 = $prop;
}
function func3()
{
return $this->pro + $this->pri2 + $this->func();
}
};
}
}
echo (new A)->func2()->func3();//9
8.
/**
* 魔术方法 __call和__callStatic
*/
class A
{
function __call($name, $params)
{
echo '方法名是' . $name . ',参数为:';
var_dump($params);
}
/**
* 去掉static,会有Warning报错
*/
static function __callStatic($name, $params)
{
echo '静态方法名是' . $name . ',参数为:';
var_dump($params);
}
}
$a = new A;
$a->say(1, 2);
A::say(['3', '4']);
/*
方法名是say,参数为:
F:\wamp\www\test.php:7:
array (size=2)
0 => int 1
1 => int 2
静态方法名是say,参数为:
F:\wamp\www\test.php:13:
array (size=1)
0 =>
array (size=2)
0 => string '3' (length=1)
1 => string '4' (length=1)
*/