2

我是 php oop 的新手。我在显示我的字段值时遇到了麻烦。我这里有 ff 课程。

public static function getAll()
{

    self::conn();

    try
    {

        $sql = "SELECT * FROM dbo.guitar";

        $q = self::$db->prepare($sql);
        $q->execute();
        $results = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,
                "Guitar",
                array('id', 'make', 'model', 'colour', 'price'));

    }
    catch (Exception $e)
    {
        print "Error!: " . $e->getMessage();
    }

    return $results;    
}

我希望它从差异字段中显示。这是我的代码:

$guitars = Guitar::getAll();

当我尝试使用print_r

我想要的是这样的。

echo $row['field1'];  echo $row['field2']; 

先感谢您。

4

1 回答 1

1

您正在将结果作为对象获取,因此您可以这样做:

$guitars = Guitar::getAll();
foreach ($guitars as $guitar) {
  echo $guitar->getId();
  echo $guitar->getMake();
  // ... and so on
}

补充:

您需要有构造函数来设置属性,并提供公共方法来访问该属性。

class Guitar {
  private $id;
  private $make;
  private $model;
  private $color;
  private $price;

  public function __construct($id, $make, $model, $color, $price) {
    $this->id = $id;
    $this->make = $make;
    $this->model = $model;
    $this->color = $color;
    $this->price = $price;
  }

  public function getId() {
    return $this->id;
  }

  public function getMake() {
    return $this->make;
  }
  // and so on...
}
于 2012-09-24T06:54:05.160 回答