PHP类:写对象内的函数?
我不知道下面这个是否可能出现在php类对象中,就像我在javascript(jquery)中那样。PHP类:写对象内的函数?
jQuery中,我会做,
(function($){ var methods = {
init : function(options) {
// I write the function here...
},
hello : function(options) {
// I write the function here...
}
}
$.fn.myplugin = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist.');
}
return this;
};
})(jQuery);
所以,当我想打电话给内部myplugin
一个功能,我只是这样做,
$.fn.myplugin("hello");
所以,我认为,有可能是当你来写一个课程的时候,一种在php中这样做的方法?
$method = (object)array("init" => function() {
// I write the function here...
},
"hello" => function() {
// I write the function here...
}
);
编辑:
难道是这样一类?
class ClassName { public function __construct(){
//
}
public function method_1(){
$method = (object)array(
"init" => function() {
// I write the function here...
},
"hello" => function() {
// I write the function here...
}
);
}
public function method_2(){
$method = (object)array(
"init" => function() {
// I write the function here...
},
"hello" => function() {
// I write the function here...
}
);
}
}
回答:
你$.fn.myplugin
功能非常相似,在PHP中__call()
神奇的功能。但是,你必须在一个类来定义它和仿效的逻辑:
class Example { private $methods;
public function __construct() {
$methods = array();
$methods['init'] = function() {};
$methods['hello'] = function() {};
}
public function __call($name, $arguments) {
if(isset($methods[$name])) {
call_user_func_array($methods[$name], $arguments);
} else if($arguments[0] instanceof Closure) {
// We were passed an anonymous function, I actually don't think this is possible, you'd have to pass it in as an argument
call_user_func_array($methods['init'], $arguments);
} else {
throw new Exception("Method " . $name . " does not exist");
}
}
}
然后,你会怎么做:
$obj = new Example(); $obj->hello();
这不是测试,但希望这是一个开始。
回答:
class ClassName { public function __construct(){
//this is your init
}
public function hello(){
//write your function here
}
}
是你会怎么写呢
然后
$a = new ClassName() $a->hello();
叫它
回答:
PHP支持闭幕(匿名函数) 类似的jQuery看看
function x(callable $c){ $c();
}
然后用
x(function(){ echo 'Hello World';
});
以上是 PHP类:写对象内的函数? 的全部内容, 来源链接: utcz.com/qa/267092.html