【问题标题】:Passing parameters from an outside file to a class将参数从外部文件传递给类
【发布时间】:2011-02-09 17:08:35
【问题描述】:

我需要两个文件。 让我们调用控制第二个的文件:main.php,让我们调用辅助文件,即我的代码:second.php

在 second.php 我有:

<?php

class tags{

    var $theuser;
    var $thebarname;
    var $theplace;
    var $thetime;
    var $themail;

    function __construct($theuser,$thebarname,$theplace, $thetime, $themail){
       $this->theuser=$theuser;
       $this->thebarname=$thebarname;
       $this->theplace=$theplace;
       $this->thetime=$thetime;
       $this->themail=$themail;

    }

    function give_tags_theuser(){
       return $this->theuser;
    }
    function give_tags_thebarname(){
       return $this->thebarname;
    }

    function give_tags_theplace(){
       return $this->theplace;
    }

    function give_tags_thetime(){
       return $this->thetime;
    }
    function give_tags_themail(){
       return $this->themail;
    }
}


$tags = new tags("John", "Starbucks", "NY", "4:30", "example@example.com");

$user= $tags->give_tags_theuser();
$barname = $tags->give_tags_thebarname();
$place =  $tags->give_tags_theplace(); 
$time = $tags->give_tags_thetime(); 
$email = $tags->give_tags_themail();

// with the data before I will send an email using phpmailer, but that's another story
?>

在 main.php 中,我需要将变量传递给类。意思是我会删除:

$tags = new tags("John", "Starbucks", "NY", "4:30", "example@example.com");

来自 second.php,我将从 main.php 传递这些数据

我必须在 second.php 中更改什么以及 main.php 将如何更改?

如果我没有解释自己,请告诉我,我还是个学生,我可能还在搞乱词汇。

非常感谢

【问题讨论】:

    标签: php class object include


    【解决方案1】:

    如果您使用类,那么您实际上不应该在定义这些类的文件中对这些类进行操作。

    例如,鉴于您的情况,您应该在名为 tags.php 的文件中定义 tags 类,然后让您的 main.php 文件成为应用程序的运行器,因此在该文件中执行以下操作:

    require_once 'tags.php' 
    $tags = new tags("John", "Starbucks", "NY", "4:30", "example@example.com");
    
    $user= $tags->give_tags_theuser();
    $barname = $tags->give_tags_thebarname();
    $place =  $tags->give_tags_theplace(); 
    $time = $tags->give_tags_thetime(); 
    $email = $tags->give_tags_themail();
    

    这比编写在多个文件中运行应用程序的代码要好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      相关资源
      最近更新 更多