我希望我的变量可以被php中的类中的所有函数访问。 我正在提供我想要实现的示例代码。请帮帮我。
class ClassName extends AnotherClass {
function __construct(argument)
{
}
$name = $this->getName();
$city = $this->getCity();
$age = 24;
public function getName() {
return 'foo';
}
public function getCity() {
return 'kolkata';
}
public function fun1() {
echo $name;
echo $city;
echo $age;
}
public function fun2() {
echo $name;
echo $city;
echo $age;
}
public function fun3() {
echo $name;
echo $city;
echo $age;
}
}
或者,如果有任何其他方式可以减少开销。请建议
答案 0 :(得分:2)
你可以像这样实现目标:
class ClassName extends AnotherClass {
private $name;
private $city;
private $age;
function __construct(argument)
{
$this->name = $this->getName();
$this->city = $this->getCity();
$this->age = 24;
}
public function getName(){
return 'foo';
}
public function getCity(){
return 'kolkata';
}
public function fun1(){
echo $this->name;
echo $this->city;
echo $this->age;
}
public function fun2(){
echo $this->name;
echo $this->city;
echo $this->age;
}
public function fun3(){
echo $this->name;
echo $this->city;
echo $this->age;
}
}
答案 1 :(得分:0)
class ClassName extends AnotherClass
{
protected $name;
protected $city;
protected $age = 24;
public function __construct()
{
$this->name = $this->getName();
$this->city = $this->getCity();
}
...
public function fun1()
{
echo $this->name;
echo $this->city;
echo $this->age;
}
...
}
那会让你有所收获。
答案 2 :(得分:-1)
您必须将变量设置为类属性:
class ClassName extends AnotherClass {
private $name;
private $city;
private $age;
//Here we do our setters and getters
public function setName($name)
{$this->name = $name;}
public function getName()
{return $this->name;}
// you call the setters in your construct, and you set the values there
当然,您可以将它们设置为私有,公共或受保护,取决于您是否希望只能从此类或其他人访问它们。