ede*_*ter 12 php wordpress namespaces
我正在使用命名空间.
我尝试创建一个WordPress小部件(http://codex.wordpress.org/Widgets_API)
使用命名空间时,下面会出现错误,因为无法传递参数(并且没有命名空间,它显然像通常一样工作)
namespace a\b\c;
class whatever extends \WP_Widget {
function whatever() {
parent::WP_Widget('name1', 'name2');
}
// .. other functions left out
}
add_action('widgets_init',
create_function('', 'return register_widget("a\b\c\whatever");'));
Run Code Online (Sandbox Code Playgroud)
嗯...使用命名空间的'parent :: WP_Widget'的正确语法是什么?
(COMPLETE错误消息是:
Warning: Missing argument 2 for WP_Widget::__construct(), called in
C:\xampp\htdocs\wp2\wp-includes\widgets.php on line 324 and defined in
C:\xampp\htdocs\wp2\wp-includes\widgets.php on line 93
Run Code Online (Sandbox Code Playgroud)
)
调试器显示没有传递任何内容:
Variables in local scope (#14)
$control_options = Undefined
$id_base = boolean false
$name = Undefined
$widget_options = Undefined
Run Code Online (Sandbox Code Playgroud)
(只需要$ name)
Rob*_*itt 22
查看此处的文档,似乎只需要名称,但PHP的工作方式也必须定义预变量.
您有两种创建类的方法:
WP_Widget __construct ([string $id_base = false], string $name, [array $widget_options = array()], [array $control_options = array()])
WP_Widget WP_Widget ([ $id_base = false], $name, [ $widget_options = array()], [ $control_options = array()])
您应该始终使用该__construct
方法来初始化您的对象,我会像这样重写您的代码:
namespace a\b\c;
class whatever extends \WP_Widget
{
function __construct()
{
parent::__construct('name1', 'name2');
}
/*
* Other methods!
*/
}
Run Code Online (Sandbox Code Playgroud)
该WP_Widget::WP_Widget(..)
方法仅适用于PHP4,不应在PHP 5或更高版本中使用.
现在看来您使用PHP 5.3作为使用名称空间,以便您可以执行以下操作:
add_action('widgets_init', function() {
return register_widget(new a\b\c\whatever);
});
Run Code Online (Sandbox Code Playgroud)
在我看来,你的问题不在命名空间中,以下代码就像一个魅力:
<?php
namespace Foo;
class Bar {
function __construct( $foo ) {
echo "$foo\n";
}
}
namespace Foo\Bar;
class Foo extends \Foo\Bar {
function __construct( ) {
parent::__construct( "This should work." );
}
}
$foo = new \Foo\Bar\Foo( );
Run Code Online (Sandbox Code Playgroud)
如果您收到错误消息,说明其内容可能会有所帮助。
归档时间: |
|
查看次数: |
22290 次 |
最近记录: |