PHP 方法重写,参数不同,报错: Declaration
前言
php 方法重写,参数不同,报错: Declaration of should be compatible with that
本人laravel报错提示
这里是ErrorException: Declaration of Module\Article\Controller\Mobile\ListController::tagsVideo($type, $tagsStr) should be compatible with Module\Article\Controller\Web\ListController::tagsVideo($type, $tagsStr, $page = NULL)
因为我这里是继承的关系,这是手机端的控制器继承PC控制器。
这边 一个方法 tagsVideo()
是被重写的方法,但是一直报错,查询了一下,原来是 php 继承 重写 函数,则参数不一致问题。
// MOBILE
/**
* 视频标签内容页 function
*
* @param [str] $type
* @param [str] $tagsStr
* @param [int] $page
* @return void
* @author bobo <email@email.com>
* @date 2019-12-18
*/
public function tagsVideo($type, $tagsStr,$page=null)
{
$tags = $this->parseTags($tagsStr);
$count = 10;
// 加上 $page
// 读取缓存版
$articles = $this->paging($this->relationsCache('tagsVideo',$tags, $count*10, Article::CATEGORY_VIDEO), $count, $page);
// $articles = $this->paging($this->relations($tags, $count*10, Article::CATEGORY_VIDEO), $count, $page);
// select * from a where id = 5 limit
$urlPattern = $this->linkFactory->videoTag($type, $tags);
return $this->render("articles", $urlPattern, [
"tagName" => $tagsStr,
"articles" => $articles,
"matchType" => $type,
"tdk" => [
"topic" => $this->findTdkTags($tagsStr),
]
]);
}
//PC
public function tagsVideo($type, $tagsStr,$page=null)
{
$tags = $this->parseTags($tagsStr);
$count = 10;
// 加上 $page
$articles = $this->paging($this->relations($tags, $count*10, Article::CATEGORY_VIDEO), $count, $page);
$urlPattern = $this->linkFactory->videoTag($type, $tags);
return $this->render("articles", $urlPattern, [
"tagName" => $tagsStr,
"articles" => $articles,
"matchType" => $type,
"tdk" => [
"topic" => $this->findTdkTags($tagsStr),
]
]);
}
明显看到,是有一个page 参数,我们可以给一个默认为空即可。
详细举一个例子 来讲
报错提示
<?php
abstract class A {
// 方法无参数
public static function foo(){ echo 'bar'; }
}
abstract class B extends A {
// 方法有参数
public static function foo($str){ echo $str; }
}
?>
如上面的代码:类A中的foo方法无参数,类B在继承A后重写foo方法时加入了参数,因此会产生一个类似下面E_STRICT级别的警告:
Strict standards: Declaration of ... should be compatible with that of ...
解决方法:
<?php
abstract class A {
// 方法无参数
public static function foo(){ echo 'bar'; }
}
abstract class B extends A {
// 方法有参数
public static function foo($str = NULL){ echo $str; }
}
?>
解决办法
类B在重写foo方法时为新加入的参数指定一个默认值即可。
本作品采用《CC 协议》,转载必须注明作者和本文链接
重写
和重载
了解一下@sane 我目前是重写了这个function。 你意思是,使用重载吗。
这个是重载噢
@zhp_xixi 我是重写。
@kuibatian
重写 (Override)
是子类对父类的允许访问的方法的实现过程进行重新编写, 返回值和形参都不能改变;重载 (overloading)
是在一个类里面,方法名字相同,而参数不同。返回类型可以相同也可以不同;而
php
中的 重载@sane 可能是我代码贴的有问题,重新贴了一下。这样子是重写是的。
没细看,但是,是
覆盖
了父类的方法么?@qufo 是的覆盖。
PHP里面没有重载,只有重写。
PHP 里面没有重载,只有重写。重载只是间接用另一种方式去实现而已。