Передача параметров из внешнего файла в класс - PullRequest
0 голосов
/ 09 февраля 2011

Мне нужно иметь два файла. Давайте назовем файл, управляющий вторым: 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 для этого?

Если я не объяснил себя, скажите, пожалуйста, я все еще студент, и, вероятно, все еще не в курсе словарный запас.

Большое спасибо

1 Ответ

0 голосов
/ 09 февраля 2011

Если вы используете классы, тогда вам не следует выполнять операции над этими классами внутри файлов, которые определяют эти классы.

Например, учитывая вашу ситуацию, вы должны определить класс tags внутри файла с именем tags.php, а затем сделать файл 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();

Это лучше, чем писать код, который запускает ваше приложение в нескольких файлах.

...