在PHP中,我可以指定具有字段的接口,还是PHP接口仅限于函数?
<?php
interface IFoo
{
public $field;
public function DoSomething();
public function DoSomethingElse();
}
?>
Run Code Online (Sandbox Code Playgroud)
如果没有,我意识到我可以在接口中公开一个getter作为函数:
public GetField();
Run Code Online (Sandbox Code Playgroud)
Gor*_*don 48
您无法指定成员.你必须通过吸气剂和制定者表明他们的存在,就像你一样.但是,您可以指定常量:
interface IFoo
{
const foo = 'bar';
public function DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
见http://www.php.net/manual/en/language.oop5.interfaces.php
小智 21
迟到的答案,但要获得此处所需的功能,您可能需要考虑包含字段的抽象类.抽象类看起来像这样:
abstract class Foo
{
public $member;
}
Run Code Online (Sandbox Code Playgroud)
虽然你仍然可以拥有界面:
interface IFoo
{
public function someFunction();
}
Run Code Online (Sandbox Code Playgroud)
然后你有这样的孩子班:
class bar extends Foo implements IFoo
{
public function __construct($memberValue = "")
{
// Set the value of the member from the abstract class
$this->member = $memberValue;
}
public function someFunction()
{
// Echo the member from the abstract class
echo $this->member;
}
}
Run Code Online (Sandbox Code Playgroud)
对那些仍然充满好奇和兴趣的人来说,还有另一种解决方案.:)
小智 13
使用getter setter.但是在许多类中实现许多getter和setter可能会很繁琐,而且它会使类代码混乱.而你重复自己!
从PHP 5.4开始,您可以使用特征为类提供字段和方法,即:
interface IFoo
{
public function DoSomething();
public function DoSomethingElse();
public function setField($value);
public function getField();
}
trait WithField
{
private $_field;
public function setField($value)
{
$this->_field = $value;
}
public function getField()
{
return $this->field;
}
}
class Bar implements IFoo
{
use WithField;
public function DoSomething()
{
echo $this->getField();
}
public function DoSomethingElse()
{
echo $this->setField('blah');
}
}
Run Code Online (Sandbox Code Playgroud)
如果您必须从某个基类继承并需要实现某个接口,这是特别有用的.
class CooCoo extends Bird implements IFoo
{
use WithField;
public function DoSomething()
{
echo $this->getField();
}
public function DoSomethingElse()
{
echo $this->setField('blah');
}
}
Run Code Online (Sandbox Code Playgroud)
您不能在以下内容中指定属性interface
:仅允许方法(并且有意义,因为接口的目标是指定API)
在PHP中,尝试在接口中定义属性应该引发致命错误:这部分代码:
interface A {
public $test;
}
Run Code Online (Sandbox Code Playgroud)
会给你 :
Fatal error: Interfaces may not include member variables in...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
35395 次 |
最近记录: |