Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于匿名函数和闭包函数 #6

Closed
bestcyt opened this issue Jul 27, 2018 · 5 comments
Closed

关于匿名函数和闭包函数 #6

bestcyt opened this issue Jul 27, 2018 · 5 comments

Comments

@bestcyt
Copy link

bestcyt commented Jul 27, 2018

image
大佬,感觉应该说:在PHP中 匿名函数跟闭包函数是差不多的?

@xianyunyh
Copy link
Owner

在PHP中,匿名函数的作用,大部分作用是作为一次性函数,回调,很少作为向JavaScript那样使用闭包

$fn = function(){};

$fn();

array_map(function(){},$array);

javascript中 为了保存内部变量

var f = function(){
   $a=1
//产生闭包
   return function(){
   return $a++
}
}

f1 = f()
f1()//1
f1()//2

@bestcyt
Copy link
Author

bestcyt commented Jul 27, 2018

嗯嗯,对的,js中闭包是能访问到外部变量的,而PHP需要use;我的意思是在那句话前加个(在PHP中),会不会比较严谨点?哈哈哈我就无聊随便说说:)

@xianyunyh
Copy link
Owner

没事! @bestcyt 相互交流而已。 PHP的匿名函数 一般就是作回调。Js的匿名函数只要是为了保存一些内部变量,产生闭包。 js的作用域和PHP的也不太一样,所以两个语言相互理解一下

$a = 10;//外部变量 非全局 
function f () {
echo $a; //内部的$a 未定义
}

# use 将a加到函数的作用域下
$f1 = function () use ($a) {
    echo $a;
};
$f1();
var a =  10 //全局变量
function f(){
alert(a)//10
}

@bestcyt
Copy link
Author

bestcyt commented Jul 27, 2018

image
@xianyunyh 大佬这边子类应该是不能用parent来获取父类的保护属性,要用this,你看看是不是酱紫?

@xianyunyh
Copy link
Owner

@bestcyt 可能我写错了! 以下是用法和官方的介绍。

感谢指正

范围解析操作符(也可称作 Paamayim Nekudotayim)或者更简单地说是一对冒号 ::,可以用于访问 静态成员类常量,还可以用于覆盖类中的属性和方法。

class A
{
    const PI = 3.14;
    public static $static_var = "A的静态变量";
    public function __construct()
    {
        echo "this is A" . "\n";
    }
}

class B extends A
{

    public function __construct()
    {
        parent::__construct();
    }
    public function test()
    {
        echo parent::PI . "\n";
        echo parent::$static_var;
    }
}

(new B())->test();

参考链接

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants