tags:

views:

79

answers:

2

Hi Im trying to develop a oop php driven blog. Im new to the oop way in php so its going quite slow. I have a class BlogPost were I have created the private variables for the rows in my blog field in he db and getters and setters for them example:

function getCreated() {
    return $this-$created;
}

function setCreated($created) {
     $this->$created = $created;
}

is this the way to do it?! I think Im on the right track but Im not sure. Do anyone have any input?! maybe some tips on good tutorials on how to create a blog oop php style. Found one at net.tuts but Im not really liking it. Thanks!

Regards

+5  A: 

You are close, try

function getCreated() {
    return $this->created;
}

function setCreated($created) {
     $this->created = $created;
}
Zoidberg
@zoidberg: thanks for your feedback I should have known that, a minor typo we can call that:). One thing though how would you create the constructor for this? I was thinking something like this: public function __construct($id, $created, $modified, $author, $title, $body) { $this->$id = }
Tim
and again the typo: `$this->$id` should be `$this->id`
jigfox
Yeah, just get rid of the dollar sign infront of the property. $this->$id would look for a property with the same name as the value in the variable $id, which you don't want.
Zoidberg
+2  A: 

Personally, I avoid getters and settings and just use public properties. I then use the __set() magic method to listen for properties being set and add the key to a private $dirty array. I can then loop over these when saving a record. For example:

class BlogPost {

    public $id;
    public $title;
    public $content;

    private $dirty;

    function __set($key, $value) {
        $this->$key = $value;
        $this->dirty[] = $key;
    }

    function save() {
        if (isset($this->id) && intval($this->id) > 0) {
            // do UPDATE query
        } else {
            // do INSERT query
        }
    }
}

Then to use:

$id = (isset($_GET['id'])) ? intval($_GET['id']) : null;

$post = new BlogPost();
$post->title = $_POST['title'];
$post->content = $_POST['content'];
$post->save();

Very primitive, but should give you an idea of how to implement this theory for yourself.

Martin Bean