dongzhong1929 2015-01-07 20:12
浏览 21
已采纳

在PHP函数中使用参数文本

I am a little new to the PHP world and despite my googling and manual reading, I can't

I am currently (ethically!) scraping a website that has a number of different categories (let us call them 'alpha', 'beta', 'gamma').

Currently, I go through these steps:

  1. Load the file
  2. Locate the correct table (php_siomple_dom)
  3. Then go through the elements to grab the information.

    $alpha_one = $element -> find etc;
    $alpha_two = $element -> find etc;
    $alpha_n   = $element -> find etc;
    
    $beta_one  = $element -> find etc;
    $beta _two = $element -> find etc;
    $beta_n    = $element -> find etc;
    
  4. All of the tables are the same for alpha, beta, gamma; thus I would like to write a function, but I am struggling with how to include the argument name in the variables I create. This was my idea, but it does not work.

    function grab($argument) {
    
        $argument . "_one" = $element -> find etc;
        $argument . "_two" = $element -> find etc;
        $argument . "_n"   = $element -> find etc;
    
    }
    

Thus, I could use:

grab('alpha');

grab('beta');

grab('gamma');

without having to write out the code for each table

I've looked into 'magic methods', but cannot swing it into working. I would really appreciate if some PHP wizard could shed some light upon this. Thank youu!

  • 写回答

3条回答 默认 最新

  • dongrong9053 2015-01-07 20:17
    关注

    That code is rather pointless. the $argument . "_one" variable would exist ONLY within the function, and be destroyed when the function returns. You probably want something more like this:

    function grab($argument) {
        $data = array();
        $data[$argument . "_one"] = ...
        $data[$argument . "_two"] = ...
        etc...
        return ($data);
    }
    

    Essentially: build an array with dynamic key names, based on your $argument, then return the entire array to the calling context.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序