构造类变量

时间:2014-03-26 18:05:39

标签: php class constructor

我正在尝试在全球范围内制作我的班级变量'我的Web应用程序,因此当您调用它们时,它们可以在其他类中轻松地在整个Web应用程序中使用。这是我的Web应用程序的文章类。

class Articles {

   //  Defined variables that constructs an Article
   private $id
   private $title
   private $summary
   private $content
   private $author

   public function __construct($id, $title, $summary, $content, $author) {
      //  Constructs our Article by default
      $this->id      = $id;
      $this->title   = $title;
      $this->summary = $summary;
      $this->content = $content;
      $this->author  = $author;
   }
}

这是我的init.php文件

//  Require the Articles and ArticlesHandler Class
require 'Articles/Articles.php';
require 'Articles/ArticlesHander.php';

如果我需要在ArticlesHandler中调用$ title,它是否可以使用$ title或者是否需要使用$ this-> title来调用它?或者有更好的方法来做到这一点吗?

2 个答案:

答案 0 :(得分:-1)

您可以轻松返回值,将它们保存在变量中并将其声明为全局值,例如

public function show() {
    return $this->id;
}

然后在你开始上课后,你可以这样做

$id = $class->show();
global $id;

另一种方法是将类中的变量范围更改为public

然后您可以轻松地执行以下操作

$id = $class->id;
global $id;

答案 1 :(得分:-2)

    You need to create an object of the class to access the variables. In your case it will be 

        $articles = new Articles(1,'mytitle','test','mycontent','myauthor');
        echo $articles->title; // mytitle

    If you can give more information on what your ArticlesHandler class is doing, I could edit my answer to your requirements.

**Edit:**

    private variables are meant to be private to the class , so they cannot be accessed outside the class.

    There are different ways to address this:
    1.  create a public function and return the private variable through it. 
    public function displayTitle(){
    return $this->title;
    }

    2. You could make ArticlesHanlder subclass of Articles and make the variables in Articles protected, so it is accessible by the classes that inherit Articles class.
    then you could just use it like $this->title in the ArticlesHanlder.