一、静态方法
class test{
function __construct($str){
echo $str.'<br>';
}
public function test() {
echo 'test <br>';
}
public static function test2() {
echo 'test2 <br>';
}
}
$test = new test("hello"); // hello
$test->test(); // test
test::test2(); // test2
// 在构造方法中使用
class B {
public function say() {
echo 'hello world !';
}
}
class A {
private static $class;
public function __construct() {
self::$class = new B; // 初始化给静态变量赋值
}
public function say() {
self::$class->say();
}
}
$a = new A();
$a->say(); // hello world !
二、接口
interface ITest {
public function sayHello(); // 接口方法
}
// 定义一个类实现这个接口
class Test implements ITest {
public function sayHello() { // 实现接口方法
echo 'hello world !';
}
}
$test = new Test();
$test->sayHello(); // hello world !
小知识:
抽象类与接口的区别:
- 抽象类中可以没有抽象方法,但有抽像方法的类都是抽象类
- 接口是通过类实现的,抽象类是通过类继承的
三、链式
// 方式一 return $this
class Test {
public function a($str) {
echo $str;
return $this; // 返回当前指针
}
public function b() {
echo 'b';
}
}
$test = new Test();
$test->a('hello ')->b(); // hello b
// 方式二 return object
class B {
public function hello() {
echo 'hello world !';
}
}
class A {
public $say;
public function __construct() {
$this->say = $this->say(); // 初始化时赋值
}
public function say() {
return new B;
}
}
$a = new A();
$a->say->hello(); // 或$a->say()->hell();
欢迎关注技术开发分享录:http://fenxianglu.cn/