构造函数
__construct:用于对对象的属性进行初始化。
比如我在Service类里面需要使用到别的类功能,如果每个方法都new一个的话,这个操作就十分麻烦,所以在构造函数里面直接初始化
注:这里情况我使用这种,也可以使用依赖注入,如果是hyperf或者java框架可以使用注解方式实现
方法重载
__call()和__callStatic():自定义函数名的时候使用
在 laravel 中尤其常见,但是开发过程中很明显这些有一部分不是静态的,比如你使用一个模型User,那么你每次实例化出来他都是一个全新的,互不影响,这里就用到了一个魔术方法__callStatic。
<?php
class Test{
public function __call($name, $arguments)
{
echo 'this is __call'. PHP_EOL;
}
public static function __callStatic($name, $arguments)
{
echo 'this is __callStatic:'. PHP_EOL;
}
}
$test = new Test();
$test->hello(); //this is __call:hello
$test::hi(); //this is __callStatic:hi
easywechat也有类似的例子:
比如在支付后回调通知
$app = Factory::payment( config('wechat.payment.default') );
进入Factory这个类里面就可以看到
<?php
/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <i@overtrue.me>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace EasyWeChat;
/**
* Class Factory.
*
* @method static \EasyWeChat\Payment\Application payment(array $config)
* @method static \EasyWeChat\MiniProgram\Application miniProgram(array $config)
* @method static \EasyWeChat\OpenPlatform\Application openPlatform(array $config)
* @method static \EasyWeChat\OfficialAccount\Application officialAccount(array $config)
* @method static \EasyWeChat\BasicService\Application basicService(array $config)
* @method static \EasyWeChat\Work\Application work(array $config)
* @method static \EasyWeChat\OpenWork\Application openWork(array $config)
* @method static \EasyWeChat\MicroMerchant\Application microMerchant(array $config)
*/
class Factory
{
/**
* @param string $name
* @param array $config
*
* @return \EasyWeChat\Kernel\ServiceContainer
*/
public static function make($name, array $config)
{
$namespace = Kernel\Support\Str::studly($name);
$application = "\\EasyWeChat\\{$namespace}\\Application";
return new $application($config);
}
/**
* Dynamically pass methods to the application.
*
* @param string $name
* @param array $arguments
*
* @return mixed
*/
public static function __callStatic($name, $arguments)
{
return self::make($name, ...$arguments);
}
}
其他
__set() 在给不可访问的属性赋值时调用
__get() 读取不可访问的属性值是自动调用
__isset() 当对不可访问的私有属性使用isset或empty时自动调用
__unset() 当对不可访问的私有属性使用unset时;自动调用
__toString()当一个类的实例对象;被当成一个字符串输出时调用