【问题标题】:Constructing Class Variables构造类变量
【发布时间】:2014-03-26 18:05:39
【问题描述】:

我正在尝试在我的 Web 应用程序的“全局范围”中创建我的类变量,以便在您调用它们时可以轻松地在其他类中使用它们并在整个 Web 应用程序中使用它们。这是我的 Web 应用程序的 Articles 类。

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 来调用它?还是有更好的方法来做到这一点?

【问题讨论】:

  • 这里实际上没有创建任何类实例......不要将类定义与类变量混淆(除非您指的是类实例,否则没有这样的东西)并了解自动加载器而不是处理包含为您的 init.php 文件中的所有内容
  • 我在文件中调用类的实例。 init 是 Db、文章、成员等的全部内容。该实例在 index.php 中调用。很抱歉造成混乱。
  • @Traven 您能否编辑您的问题以显示创建实例的文件(例如$article = new Article(1, 'Hello', 'World', '!', 'me');

标签: php class constructor


【解决方案1】:

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

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

然后在你开始你的课程之后,你可以这样做

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

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

那么你就可以轻松做到以下几点

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

【讨论】:

  • “我正在尝试将我的类变量放在‘全局范围’中”@user2411276,我只回答了 OP 的问题
  • 你真的应该告诉 OP 在全局范围内维护所有内容并不是一个好主意,并将它们介绍给依赖注入和/或工厂模式,而不是展示如何使用全局(尤其是因为你也没有做得特别好)
【解决方案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.

【讨论】:

  • 我一开始没有正确阅读这个问题,因为问题是要使 Articles 类中的变量全局可用,您应该将它们声明为 public。
猜你喜欢
  • 2019-05-25
  • 2014-12-16
  • 2018-06-06
  • 2023-03-24
  • 2016-05-23
  • 2017-05-01
  • 2022-01-18
  • 1970-01-01
  • 2018-02-22
相关资源
最近更新 更多