问题描述
我有一个Laravel 4.2应用程序,可以与PHP5一起使用,没有任何问题.由于我安装了运行PHP7的新游民箱,因此在运行模型时,如功能名称与类名称(关系功能)相同,将出现错误:
I have a Laravel 4.2 application which works with PHP5 without any problems. Since I installed a new vagrant box running PHP7 an error appears as soon as I run a model where the name of a function is the same as the class name (relationship-function) like this:
<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Participant extends \Eloquent
{
use SoftDeletingTrait;
[...]
public function participant()
{
return $this->morphTo();
}
[...]
}
我收到以下错误消息:
所以直到今天我才知道,在PHP4中,具有相同名称的方法是类的构造函数.唔.我确实是一个糟糕的程序员.但是,在这种情况下,根据我对PHP7中发生的情况的了解,他们纠正了我的失败,因为我从不希望将此函数用作构造函数,因为它仅定义了Eloquent关系.
So what I didn't know until today is, that in PHP4 methods with the same name were the contructor of a class. Hmm. I am really a bad programmer... But in this case, from my understanding of what is happening in PHP7, they correct a failure of mine as I never wanted to use this function as a constructor, since it defines only an Eloquent relationship.
但是如何摆脱此消息?据我了解,在PHP4中我的代码有错误,但在PHP7中不是,对吧?如果不需要,我不想重构此功能,因为它已在多个地方使用.
But how can I get rid of this message? As I understand this, in PHP4 my code was buggy, but not in PHP7, right? If not necessary I do not want to refactor this function, as it is used in several places.
任何人都可以解释我做错了什么以及为什么它可以与较旧的PHP版本一起使用吗?
Can anybody explain what I am doing wrong and why it worked with older PHP versions?
谢谢!
推荐答案
不完全是. PHP4样式的构造函数仍可在PHP7上使用,它们已被弃用,并且会触发不赞成使用的警告.
Not quite. PHP4-style constructors still work on PHP7, they are just been deprecated and they will trigger a Deprecated warning.
您可以做的是定义一个__construct
方法,甚至是一个空方法,这样就不会在新创建的类实例上调用php4-constructor方法.
What you can do is define a __construct
method, even an empty one, so that the php4-constructor method won't be called on a newly-created instance of the class.
class foo
{
public function __construct()
{
// Constructor's functionality here, if you have any.
}
public function foo()
{
// PHP4-style constructor.
// This will NOT be invoked, unless a sub-class that extends `foo` calls it.
// In that case, call the new-style constructor to keep compatibility.
self::__construct();
}
}
new foo();
它与较旧的PHP版本一起使用仅是因为构造函数没有获得返回值.每次创建Participant实例时,都隐式调用participant
方法,仅此而已.
It worked with older PHP versions simply because constructors don't get return value. Every time you created a Participant instance, you implicitly call the participant
method, that's all.
这篇关于PHP7构造函数类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!