PHP. What should I call the information stored in my class?

I have a class named Page with a private property currently called _pageData that stores all of the information (like title, content, keywords, etc.).

However, it doesn't look that good to me when I reference it $ this → _ pageData. I want to think of a better name, and I would guess that there is probably a standard or "best" name / prefix / suffix for this kind of thing. I was thinking about "_assets".

May I ask what you have used in the past, an unambiguous name that didn't take you to the next track, add some data to it and go "Oh no, now my array has data that is out of scope for the variable name." This has happened to me several times, so I would like to see what has been proven to work.

thank

+1


source to share


2 answers


class Page {
    public $title = '';
    public $keywords = array();
    public $content = '';
    // etc.
}

$page = new Page();
echo '<title>' . $page->title . '</title>';
echo $page->content;

      

Or you can use accessors / get-set etc. to protect your data, allow persistent modification, or whatever. This allows lazy initialization and lazy writing (not sure if there is a suitable term for the latter). Example:

class Page {
    private $data = array('title' => '', 'keywords' => array(), 'content' => '');

    public __get($name) {
        if(isset($this->data[$name]))
            return $this->data[$name];

        /* You probably want to throw some sort of PHP error here. */
        return 'ERROR!';
    }
}

$page = new Page();
echo '<title>' . $page->title . '</title>';
echo $page->content;

      

(see overloading in the PHP5 manual for more details.)



Note that you can hide the $ data members or even change them or add new ones ($ page-> contentHTML can convert markdown to HTML, for example).

The use of the name _pageData

is redundant for the Page class. You already know this page, so you are repeating the information ($ currentPage -> _ pageData vs. $ currentPage->).

I also find associative arrays a little dirtier for this kind of thing, but they might be needed if you want a truly dynamic system. Regardless, you can implement your templating system to access class members by name ( $member = 'title'; echo $page->$member; // echoes $page->title

), assuming that this is what you wanted for the array (other than a simple database query, which you can use list () for).

+2


source


This is very specific and I don't think there is a "standard" or "best practice". Just call it what you think best. On my own I would just call this "data" as Page is a class, $ this = Page, so Page-> Data. That would be enough for me.



I can't think of a better name ... Perhaps this sounds strange because you are using the _ prefix? I don't like using these prefixes, especially in PHP, it doesn't make a lot of sense, but that's just me.

0


source







All Articles