好了,我现在有另一个问题,我想将一个或多个变量从一个函数发送到另一个函数,如下所示:
class test{
var $text2;
function text1($text1){ // This will catch "This is text" from $text variable.
$text1 = $this -> text2; // Giving $text1 value to $text2
return $this -> text2; // Now here is the trouble i think, i want to send the variable to the next function that is text2(). How do i do that?
}
function text2($text2){ // Here is the place that says undefined variable i want the variable $text2 from function text1() to be called here.
echo $text2; // Now the variable $text2 should echo "This is text".
}
}
$test = new test();
$text1 = "This is text"; // Assigning value to the variable.
$test -> text1($text1); // Passing the variable as parameter in the function text1().
echo $test -> text2($text2); // Trying to display the value of $text2 that is "This is text".
答案 0 :(得分:8)
您的代码遇到麻烦主要是因为它非常难以阅读!您的函数和变量具有相同的名称错误,并且它们通常是错误变量和函数名称!
以下是您的课程外观的示例,我在' TextPuzzler'中命名。因为@Matteo Riva的评论。
class TextPuzzler
{
protected $myText;
public function setMyText($text)
{
$this->myText = $text;
}
public function getMyText()
{
return $this->myText;
}
public function printMyText()
{
echo $this->myText;
}
}
$puzzler = new TextPuzzler();
$text = "This is a random text";
//this is how you set your text
$puzzler->setMyText($text);
//this is how you echo it via a special echo function, not really needed ...
$puzzler->printMyText();
//... because you can also use the getter and echo it like this
echo $puzzler->getMyText();
答案 1 :(得分:1)
它不是函数而是类方法。你不必在课堂内传递任何东西,你只需要设置类变量
答案 2 :(得分:0)
Markus声明的问题是变量名和函数名之间存在冲突。此外,赋值在函数text1,php中向后,而不是smalltalk。
答案 3 :(得分:-1)
尝试
班级考试{
var $ text2;
function text1($ text1){//这会 从$ text中抓住“这是文本” 变量
$text2 = $text1; // Giving $text1 value to $text2 $this->text2($text2);
}
function text2($ text2){
echo $text2; // Now the variable $text2 should echo "This is text".
}
}
$ test = new test();
$ text1 =“这是文字”; //分配 值变量。
$ test - >文本1($文本1); //传递 变量作为函数中的参数 文本1()。
$ test - >文本2($文本2); // 尝试去 显示$ text2的值 “这是文字”。
答案 4 :(得分:-1)
我认为你只是有一个分配错误。
在text1函数
中尝试以下操作
function text1($text1){ // This will catch "This is text" from $text variable.
$this->text2 = $text1; //CHANGE HERE
return $this->text2;
}
function text2(){ //CHANGE HERE
echo $this->text2;
}
作业从右到左发生。
左=右;
左侧将获得右侧的值。
答案 5 :(得分:-1)
当你创建text1函数时,我认为代码应该是这样的
var $text2;
function text1($ text1){//这将从$ text变量中捕获“This is text”。
text2 = $text1; // Giving $text1 value to $text2
return text2; // Now here is the trouble i think, i want to send the variable to the next function that is text2(). How do i do that?
}
function text2($text2){ // Here is the place that says undefined variable i want the variable $text2 from function text1() to be called here.
echo $text2; // Now the variable $text2 should echo "This is text".
}
还有一件事$ text2应该是全局变量