我习惯在php函数中设置和声明我的参数,如下所示:
function foo($ length = 24){...
现在我想用类功能来做到这一点:
class foo{
function configuration() {
$this->defaultLength = 24;
}
function foo() {
$this->configuration();
}
function test($length = $this->defaultLength) {...
致电:
$r = new foo();
$r->test();
我收到此错误消息: 解析错误:语法错误,/ www / htdo中意外的'$ this'(T_VARIABLE)..
如何在php类中定义和声明变量?
答案 0 :(得分:2)
我会这样做:
class foo
{
const DEFAULT_LENGHT = 24;
public function test($length = self::DEFAULT_LENGHT)
{
var_dump($length);
}
}
$foo = new foo();
$foo->test(); // // int(24)
如果需要在运行时更改该值,可以执行以下操作:
class foo
{
protected $default_lenght = 24;
public function setDefaultLenght($lenght)
{
$this->default_lenght = $lenght;
}
public function test($length = null)
{
$length = $length ?: $this->default_lenght;
var_dump($length);
}
}
$foo = new foo();
$foo->test(); // int(24)
$foo->setDefaultLenght(42);
$foo->test(); // int(42)
答案 1 :(得分:1)
您无法在功能签名中引用$this
。你可以这样做:
public function test ($length = null) {
if ($length === null) {
$length = $this->defaultLength;
}
}
答案 2 :(得分:1)
您可以使用函数签名元素构建一个数组,过滤它们并将其与默认配置合并,调用您需要的所有函数。 我做了一个简单的例子,用不同的函数定义了2个参数。
class foo{
private $configuration;
private function buildDefaultConfiguration() {
return $configuration = array(
'defaultLength' => $this->getDefaultLength(),
'defaultWidth' => $this->getDefaultWidth(),
);
}
public function __construct($givenLength = null, $givenWidth = null) {
$givenConfiguration = array(
'defaultLength' => $givenLength,
'defaultWidth' => $givenWidth
);
$givenConfiguration = array_filter($givenConfiguration);
$defaultConfiguration = $this->buildDefaultConfiguration();
$this->configuration = array_merge($defaultConfiguration, $givenConfiguration);
}
public function test()
{
echo $this->configuration['defaultLength'] . ' - ' . $this->configuration['defaultWidth'];
}
private function getDefaultLength()
{
return 24;
}
private function getDefaultWidth()
{
return 12;
}
}
$foo1 = new foo(13,14);
$foo2 = new foo();
$foo3 = new foo(null, 66);
$foo4 = new foo(66);
$foo1->test();
//result is 13 - 14
$foo2->test();
//result is 24 - 12
$foo3->test();
//result is 24 - 66
$foo4->test();
//result is 66 - 12
您可以查看实时工作示例here,虽然格式不是很好 希望这能帮助你
答案 3 :(得分:0)
class foo{
//set the default lenght first
var $defaultLength = 0;
function configuration() {
$this->defaultLength = 24;
}
function setLength($newLength){
$this->defaultLength = $newLength;
}
function test($length = null) {
//if length is null assign default
if($length == null){
$length = $this->defaultLength;
}
}
$foo = new foo();
$this->configuration();
$foo->test(); // int(24)
$foo->setLength(42);
$foo->test(); // int(42)