fishcakedev Posted March 2, 2009 Share Posted March 2, 2009 I'm trying to learn how to do OOP in PHP, and I have some experience in OOP with C++. So, I decided to make a sample application which involves two classes; Article and ArticleProp. require("ArticleProp.php"); class Article { public function __constructor(ArticleProp $properties) { $this->properties = $properties; } public function getProperties() { return $this->properties; } public function display() { print_r($this->properties->getProperties()); } private $properties; } class ArticleProp { public function __constructor() { } public function addProperty($key, $value) { $newProperty = array($key => $value); $this->properties += $newProperty; } public function getProperties() { return $this->properties; } public function getProperty($key) { while ($current = current($this->properties)) { if ($key == key($this->properties)) { return $current; } next($current); } } private $properties = array(); } Article contains an instance of ArticleProp, which is just a wrapper class for a map array that contains properties of an article, like it's title, description, content, time stamp, etc. Here's what I did to test these classes: require("Article.php"); $articleProp = new ArticleProp(); $articleProp->addProperty("title", "Lorem Ipsum Dolor Sit Amet"); $articleProp->addProperty("author", "Fishcake"); $articleProp->addProperty("timestamp", 0); $articleProp->addProperty("content", "Hello world! Hello world! Hello world! Hello world!"); $article = new Article($articleProp); $article->display(); But it doesn't work. I got an error: Fatal error: Call to a member function getProperties() on a non-object in C:\xampp\htdocs\xampp\BGT\Article.php on line 28 I think the problem is the $properties member of Article is not of ArticleProp type. How do I fix this? Is there some way to declare a variable of a certain type in PHP? Link to comment https://forums.phpfreaks.com/topic/147535-beginning-object-oriented-php/ Share on other sites More sharing options...
fishcakedev Posted March 2, 2009 Author Share Posted March 2, 2009 Oops, my bad. I found the mistake. The constructor is supposed to be called "__construct", not "_constructor". Link to comment https://forums.phpfreaks.com/topic/147535-beginning-object-oriented-php/#findComment-774477 Share on other sites More sharing options...
Mchl Posted March 2, 2009 Share Posted March 2, 2009 Yup. It's part of the concept, that method names should be verbs. You might want to take a look at autoload functionality and spl_autoload functions. Link to comment https://forums.phpfreaks.com/topic/147535-beginning-object-oriented-php/#findComment-774513 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.