分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

PHP 语法

发布时间:2023-09-06 01:39责任编辑:蔡小小关键词:PHP

匿名函数

匿名函数也叫做闭包函数 即不指定名称的函数 常用作回调函数参数的值

匿名函数演示一

$values = array(‘first‘,‘second‘,‘third‘);array_map(function($para){ ???echo $para; ???echo "<br>";}, $values);## 输出 ## first## second## third 

匿名函数演示二

$myPrint = function($msg){ ???echo $msg; ???echo "<br>";};$myPrint("hello world");## 输出 hello world

匿名函数演示三 使用外部定义变量

$name = "Json";$myPrint = function($msg) use($name){ ???echo $msg." ".$name; ???echo "<br>";};$myPrint("hello");## 输出 hello Json

后期静态绑定

在类的继承过程中 使用的类不再是当前类 而是调用的类 使用关键字 static来实现 "static::function()" 不再被解析为定义当前方法所在的类 而是在实际运行时计算得到的

静态方法演示

class A { ???public static function call() { ???????echo __CLASS__; ???????echo "<hr>"; ???} ???public static function test() { ???????self::call(); ???????static::call(); ???}}class B extends A { ???public static function call() { ???????echo __CLASS__; ???????echo "<hr>"; ???}}B::test();## 输出## A## ----------## B

非静态方法演示

class A { ???public function call() { ???????echo __CLASS__; ???????echo "<hr>"; ???} ???public function test() { ???????self::call(); ???????static::call(); ???}}class B extends A { ???public function call() { ???????echo __CLASS__; ???????echo "<hr>"; ???}}B::test();
static会根据运行时调用的类来决定实例化对象 而self是根据所在位置的类来决定实例化对象

反射

主要是用来动态的获取系统中的类 实例对象 方法等信息
class People{ ???private $name ??= ‘Json‘; ???private $age ???= 20; ???//Constructor ???public function __construct() ???{ ???????//Constructor ???} ???//print variable one ???public function getName() ???{ ???????echo $this->name."\n"; ???} ???//print variable two ???public function getAge() ???{ ???????echo $this->age."\n"; ???}}$reflector = new ReflectionClass(‘People‘);print_r($reflector->getProperties());## 输出 Array ( [0] => ReflectionProperty Object ( [name] => name [class] => People ) [1] => ReflectionProperty Object ( [name] => age [class] => People ) )print_r($reflector->getMethods());##输出 Array ( [0] => ReflectionMethod Object ( [name] => __construct [class] => People ) [1] => ReflectionMethod Object ( [name] => getName [class] => People ) [2] => ReflectionMethod Object ( [name] => getAge [class] => People ) )

trait

由于PHP是单继承的语言 但是又想实现代码复用的功能 就可以使用trait。trait不能像类一样进行实例化 而是通过关键字use添加到其它类的内部
trait sayHello { ???public function sayHello() { ???????echo ‘Hello ‘; ???}}trait sayWorld { ???public function sayWorld() { ???????echo ‘World‘; ???}}class myHelloWorld { ???use sayHello, sayWorld; ???public function say() { ???????echo ‘!!!‘; ???}}$say = new MyHelloWorld();$say->sayHello();$say->sayWorld();$say->say();## 输出 Hello World!!!

PHP 语法

原文地址:https://www.cnblogs.com/alin-qu/p/8366603.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved