在使用 PHP 类时,我注意到在类中,当我以 $this->variablename
方式将函数中的变量定义为该类的属性时,它会自动成为类的公共(public)变量那个类。
class example {
public function setstring() {
$this->string = "string";
}
}
这样
$class = new example();
echo $class->string;
输出:字符串
但是,如果我想创建只能由类内部函数访问的私有(private)变量,是否只能在 setstring()
函数内部声明它们?而不是像这样在函数之外将它们声明为私有(private)。
class example {
private $string ='';
public function setstring() {
$this->string = "string";
}
}
有人这样做的原因可能是为了整洁,以免在类开始时声明一长串私有(private)变量。
最佳答案
不,没有办法做到这一点。
在 PHP 中,您通常按字母顺序在函数上方声明所有您的类/实例属性,并带有自记录注释。这是编写类的最“整洁”和清晰的方法。还建议您完全避免使用公共(public)属性,根据需要使用 getter 和 setter。
PHP 的规范编码风格在PSR-1 中定义。和 PSR-2 .我还建议您查看 PHPDoc .
请记住,在类方法范围内声明的变量对于该方法是私有(private)的。如果您计划从其他方法访问它,您只需要一个类属性。
<?php
class Example {
/**
* Holds a private string
* @var string
*/
private $string = '';
/**
* Sets the private string variable
*/
public function setString() {
$this->string = 'This string is accessible by other methods';
$privateVar = 'This string is only accessible from within this method';
}
}
关于php - 在 PHP 类中是否可以在函数内部创建私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43416386/