duai0935 2011-04-07 06:53
浏览 60
已采纳

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

Ok now i have another problem i want to send one or more variable from one function to another like this:

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".
  • 写回答

6条回答 默认 最新

  • duanqiangwu9332 2011-04-07 07:20
    关注

    @authors of most other answers: why do you just take bad code and re-use it instead of pointing out the obvious bad practice?


    You have troubles with your code mainly because it's extremely hard to read! Your functions and variables have the same names which is bad and they are bad variable and function names in general!

    • Function names should have an 'action word' in them, a verb that shows what they do
    • Variable names should not contain numbers
    • Variable names should describe a container
    • Data types make for bad variable names ($string, $text, $int)

    Here is an example of how your class could look like, I named in 'TextPuzzler' because of @Matteo Riva 's comment.

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么