2
<?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?
?>
1

1 Answer 1

4

To your class add:

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

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

Explanation: those two methods will intercept any access to a non-existant and/or protected/private property, also preventing its creation if it does not exists.

See also http://php.net/manual/en/language.oop5.magic.php

As per @DCoder suggestion, you could also do:

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Here's an example from stackoverflow on how to throw an exception when this is done. This would be handy when developing code/unit tests where you have typos like this $obj->taxonmy = 'oops. Missing an o';
@DCoder that's possible too, it depends on how the OP wants this to be handled, I usually choose to fail silently if it is not much important.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.