douliang2087 2018-07-03 08:39
浏览 262

如何将PHP类函数中使用的变量用于另一个文件?

I am trying to fetch some variables into another file from a PHP class and could not quiet figure out the way to do it.

I am attaching a piece of dummy code which shows what exactly I am trying to do

Suppose there is a PHP class named Products.php in which there is a function getProducts() which have a variable $product_name

public function getProducts() { 
       $product_name = "Some name";  
  }

Now I want this variable $product_name to be used in a seperate file which is named as products.php. How can i use it there? I made an instance of the class like

$products = new Products($connection);

The above is just an example so please don't mind any other mistakes made, I just want to know how can i access that variable into another file!

Thanks for all the helps in advance.

  • 写回答

1条回答 默认 最新

  • doufu6130 2018-07-03 08:50
    关注

    You need to use return in the function and include the PHP file with the function in your file. The result looks somewhat like this:

    file1.php

    public function getProducts() { 
       $product_name = "Some name";  
       return $product_name;
    }
    

    file2.php

    include 'file1.php';
    $product_name = getProducts();
    

    Please keep in mind that PHP code written in this way is bad style. Here are some explanations on how PHP should be written: https://www.phptherightway.com/

    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探