Object Oriented PHP Arrays

2019-05-31 09:09发布

问题:

I've never tried OO PHP before so I decided to make a simple CMS to learn more. I am having a problem loading values into a multi-dimensional array.

class Article {
  private $index = 0;
  private $article;

  public function Article() {
   $get_articles = mysql_query("SELECT * FROM `articles`");
   while ($result = mysql_fetch_array($get_articles)) {
    echo $result["article"];

    $this->article[$index]["Tags"] = $result["tags"];
    $this->article[$index]["Categories"] = $result["categories"];
    $this->article[$index]["Date"] = $result["date"];
    $this->article[$index]["Article"] = $result["article"];
    $this->article[$index]["URL"] = $result["url"];

    $index++;
   }
  }

  public function getArticle($articleID) {
   return $this->article[$articleID]["Article"];
  }

  public function getTags($articleNumber) {

  }

  public function getCategories($articleNumber) {

  }

  public function getDate($articleNumber) {

  }
 }

The line echo $result["article"] outputs the one and only article value just fine, but apparently doesn't put it into the array?

$art = new Article();
echo $art->getArticle(0);

This doesn't output the article however. Would someone so kindly point out my noob mistake?

回答1:

You didn't initialize your array.

$this->article = array();

while ($result = mysql_fetch_array($get_articles)) {
  $this->article[$index] = array();


回答2:

You probably should define your $index variable before using it in the loop. Maybe set it to the primary key field you retrieved from your query.

<?php
$index = $result['id'];
$this->article[$index]['tags'] = ...

You also need to initialize the $article member variable.

<?php
class Article {
    private $article = array();

Remember that you define member variables within a class to be referenced via $this-> so you also don't need to define private $index = 0; in your class definition. Just define it inside the method.



回答3:

You'll notice you used $this->article but not $this->index if you want to keep track of the length for the life of the object you'll need to replace $index with $this->index



标签: php arrays oop