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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度