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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?