【问题标题】:PHP Prevent creation of attributes NOT defined in classPHP防止创建未在类中定义的属性
【发布时间】:2013-09-08 10:05:00
【问题描述】:
<?php
//Simple object to keep track of an Article
class ArchiveArticle
{
    public $timestamp;
    public $filename;
    public $slug;
    public $category;
    public $status;
    public $pubdate;
    public $ranking;
    public $newsgate_state;
    public $newsgate_story_id;
    public $newsgate_budget_id;
    public $newsgate_text_id;
    public $newsgate_profile;
    public $taxonomy;
    public $overline;
    public $net_title;
    public $headline;
    public $teasertitle;
    public $teasersummary;
    public $subhead;
    public $summary;
    public $byline_name;
    public $dateline;
    public $paragraphs = array();
    public $more_infos = array();
    public $shirttail;
    public $images = array();
}

$obj = new ArchiveArticle();
$obj->foo = 'bar'; //How can I stop this?
?>

【问题讨论】:

标签: php


【解决方案1】:

在你的班级添加:

public function __get($name) { return NULL; }

public function __set($name, $value) { }

说明:这两种方法将拦截对不存在和/或受保护/私有属性的任何访问,如果它不存在,也会阻止其创建。

另见http://php.net/manual/en/language.oop5.magic.php

根据@DCoder 的建议,您也可以这样做:

public function __get($name) {
  throw new Exception("Property $name cannot be read");
}

public function __set($name, $value) {
  throw new Exception("Property $name cannot be set");
}

【讨论】:

  • Here's an example from stackoverflow 了解如何在完成此操作后引发异常。这在开发代码/单元测试时会很方便,如果你有这样的拼写错误 $obj->taxonmy = 'oops.缺少一个 o';
  • @DCoder 这也是可能的,这取决于 OP 希望如何处理它,如果不是很重要,我通常会选择静默失败。
猜你喜欢
  • 2011-09-06
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 2020-04-10
  • 2017-09-15
  • 1970-01-01
相关资源
最近更新 更多