[php] 静态方法 接口 链式操作

一、静态方法

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 !

小知识:

抽象类与接口的区别:

  1. 抽象类中可以没有抽象方法,但有抽像方法的类都是抽象类
  2. 接口是通过类实现的,抽象类是通过类继承的

三、链式

// 方式一 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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天空还下着雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值