dousui7410 2014-08-27 15:17
浏览 19
已采纳

产生新变量以在函数外部使用的函数 - PHP

How would I alter the function below to produce a new variable for use outside of the function?

PHP Function

    function sizeShown ($size)
    {
        // *** Continental Adult Sizes ***
        if (strpos($size, 'continental-')!== false)
        {
            $size = preg_replace("/\D+/", '', $size);
            $searchsize = 'quantity_c_size_' . $size;            
        }

      return $searchsize;

Example

<?php
    sizeShown($size);
    $searchsize;  
?>

This currently produces a null value and Notice: undefined variable.

So the function takes one argument, a variable containing a string relating to size. It checks the variable for the string 'continental-', if found it trims the string of everything except the numbers. A new variable $searchsize is created which appends 'quantity_c_size_' to the value stored in $size.

So the result would be like so ... quantity_c_size_45

I want to be able to call $searchsize outside of the function within the same script.

Can anybody provide a solution? Thanks.

  • 写回答

2条回答 默认 最新

  • douyi2798 2014-08-27 15:20
    关注

    Try using the global keyword, like so:

    function test () {
        global $test_var;
        $test_var = 'Hello World!';
    }
    
    test();
    echo $test_var;
    

    However, this is usually not a good coding practice. So I would suggest the following:

    function test () {
        return 'Hello World!';
    }
    
    $test_var = test();
    echo $test_var;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动