Jump to content

Beginning Object Oriented PHP


fishcakedev

Recommended Posts

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.