在PHP中:如何调用之前在另一个函数内定义的函数内的$变量? [英] In PHP: How to call a $variable inside one function that was defined previously inside another function?
问题描述
我刚刚开始使用面向对象的PHP,并且遇到以下问题:
我有一个包含一个包含特定脚本的函数的类。我需要在同一个类的另一个函数中调用位于该脚本中的变量。
例如:
class helloWorld {
function sayHello(){
echoHello;
$ var =World;
}
函数sayWorld(){
echo $ var;
}
}
在上述例如,我想调用$ var,它是在前一个函数中定义的变量。这不起作用,所以我怎么做到这一点?
您应该在类中创建var,而不是函数,因为当函数结束变量将被取消设置(由于函数终止)...
class helloWorld {
private $ var;
函数sayHello(){
echoHello;
$ this-> var =World;
}
函数sayWorld(){
echo $ this-> var;
}
}
?>
如果您将变量声明为 public
,它可以被所有其他类直接访问,而如果你声明变量为 private
,它只能在同一个类中访问。
<?php
Class First {
private $ a;
public $ b;
public function create(){
$ this-> a = 1; //没问题
$ thia-> b = 2; //没问题
}
公共函数geta(){
return $ this-> a;
}
private function getb(){
return $ this-> b;
第二类{
函数test(){
$ a = new第一个; //创建一个First Class的对象$ a。
$ a-> create(); //调用公共函数create ..
echo $ a-> b; //在类中确定var是公共的,并且可以在任何地方访问
echo $ a-> a; //在hte类中的问题var是私有的
echo $ a-> geta(); //确定类中的A值是通过公共函数获得的,类中的值$ a不能正确访问
echo $ a-> getb(); //错误的getb函数是私人的,它只能从类里面访问
}
}
?>
I'm just starting with Object Oriented PHP and I have the following issue:
I have a class that contains a function that contains a certain script. I need to call a variable located in that script within another function further down the same class.
For example:
class helloWorld {
function sayHello() {
echo "Hello";
$var = "World";
}
function sayWorld() {
echo $var;
}
}
in the above example I want to call $var which is a variable that was defined inside a previous function. This doesn't work though, so how can I do this?
you should create the var in the class, not in the function, because when the function end the variable will be unset (due to function termination)...
class helloWorld {
private $var;
function sayHello() {
echo "Hello";
$this->var = "World";
}
function sayWorld() {
echo $this->var;
}
}
?>
If you declare the Variable as public
, it's accessible directly by all the others classes, whereas if you declare the variable as private
, it's accessible only in the same class..
<?php
Class First {
private $a;
public $b;
public function create(){
$this->a=1; //no problem
$thia->b=2; //no problem
}
public function geta(){
return $this->a;
}
private function getb(){
return $this->b;
}
}
Class Second{
function test(){
$a=new First; //create object $a that is a First Class.
$a->create(); // call the public function create..
echo $a->b; //ok in the class the var is public and it's accessible by everywhere
echo $a->a; //problem in hte class the var is private
echo $a->geta(); //ok the A value from class is get through the public function, the value $a in the class is not dicrectly accessible
echo $a->getb(); //error the getb function is private and it's accessible only from inside the class
}
}
?>
这篇关于在PHP中:如何调用之前在另一个函数内定义的函数内的$变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!