返回 2. 何时需要使用
PHP 子类覆盖父类方法?这里有解决方案
php
2024-03-31 19:17:25
PHP 中子类覆盖父类方法的解决方案
问题
当你在 PHP 中有一个继承关系,子类的方法会覆盖父类的方法。这可能会导致意料之外的行为,例如失去父类方法的功能。
解决方法
为了解决这个问题,你需要在子类的构造方法中使用 parent
来调用父类的构造方法,并传递父类构造方法所需的所有参数。这将确保子类的方法不会覆盖父类的方法,而是扩展它们。
修改后的子类构造方法
public function __construct(
MetadataInterface $metadata,
RequestConfigurationFactoryInterface $requestConfigurationFactory,
?ViewHandlerInterface $viewHandler,
RepositoryInterface $repository,
FactoryInterface $factory,
NewResourceFactoryInterface $newResourceFactory,
ObjectManager $manager,
SingleResourceProviderInterface $singleResourceProvider,
ResourcesCollectionProviderInterface $resourcesFinder,
ResourceFormFactoryInterface $resourceFormFactory,
RedirectHandlerInterface $redirectHandler,
FlashHelperInterface $flashHelper,
AuthorizationCheckerInterface $authorizationChecker,
EventDispatcherInterface $eventDispatcher,
?StateMachineInterface $stateMachine,
ResourceUpdateHandlerInterface $resourceUpdateHandler,
ResourceDeleteHandlerInterface $resourceDeleteHandler,
Sender $sender,
ChannelContextInterface $channelContext,
LocaleContextInterface $localeContext
) {
parent::__construct(
$metadata,
$requestConfigurationFactory,
$viewHandler,
$repository,
$factory,
$newResourceFactory,
$manager,
$singleResourceProvider,
$resourcesFinder,
$resourceFormFactory,
$redirectHandler,
$flashHelper,
$authorizationChecker,
$eventDispatcher,
$stateMachine,
$resourceUpdateHandler,
$resourceDeleteHandler
);
$this->sender = $sender;
$this->channelContext = $channelContext;
$this->localeContext = $localeContext;
}
常见问题解答
1. 为什么会出现这种情况?
PHP 中的子类方法覆盖父类方法是一种预期行为。它允许子类定制或扩展父类行为。
2. 何时需要使用 parent
?
你需要使用 parent
来调用父类的方法,而不是覆盖它们。这在需要继承和扩展父类行为时尤其有用。
3. 我可以传递额外的参数吗?
否,在调用 parent
时只能传递父类构造方法所需的参数。
4. 为什么我的子类方法仍然没有执行?
检查你的子类构造方法是否正确调用了 parent
,并确保传递了所有必需的参数。
5. 有没有其他方法来解决这个问题?
除了使用 parent
之外,另一种方法是使用 static
关键字在子类中调用父类方法。然而,这在某些情况下可能不是一个理想的解决方案。
结论
解决子类方法覆盖父类方法的问题非常简单,只需在子类的构造方法中正确使用 parent
。这将确保子类可以扩展和定制父类行为,同时仍然保持对父类方法的访问。