如何在php的同一页面中将变量从一个函数传递到另一个函数?

Kes*_*air -1 php variables class function

好了,我现在有另一个问题,我想将一个或多个变量从一个函数发送到另一个函数,如下所示:

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".
Run Code Online (Sandbox Code Playgroud)

mar*_*kus 8

大多数其他答案的@authors:为什么你只是采取不好的代码并重新使用它而不是指出明显的不良做法?


您的代码遇到麻烦主要是因为它非常难以阅读!您的函数和变量具有相同的名称,这些名称很糟糕,它们通常是错误的变量和函数名称!

  • 函数名称中应包含一个"动作词",一个动词,显示它们的作用
  • 变量名称不应包含数字
  • 变量名称应描述容器
  • 数据类型产生错误的变量名称($ string,$ text,$ int)

这是一个关于你的课程如何看起来的例子,我在'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();
Run Code Online (Sandbox Code Playgroud)