我如何使这个功能成为一个类?

时间:2009-09-09 03:07:18

标签: php function class

我一直在创建函数的时间太长而没有把我的代码带到'类'。

我通过示例很好地学习,我只是想把这个简单的函数转换成一个类,这样我就可以比较一些我不知道的东西......

采取以下功能:

function affiliateName($affiliateID) {

$sql = 'SELECT * FROM affiliates WHERE uID="' . $affiliateID . '" ';

$res = mysql_query($sql);

$row = mysql_fetch_array($res);

$affiliateName = $row['firstName'] . ' ' . $row['lastName'];

return $affiliateName;

}

我怎么能成为一个班级?

3 个答案:

答案 0 :(得分:4)

<?php
class AffiliateModel
{
    public function first($id)
    {
        $sql = 'SELECT *, CONCAT(firstName, ' ', lastName) AS qualifiedName FROM affiliates WHERE uID="' . $id . '" LIMIT 1';
        $res = mysql_query($sql);

        return mysql_fetch_object($res);
    }
}

$model = new AffiliateModel();
$a = $model->first($id);
echo $a->qualifiedName;
?>

答案 1 :(得分:2)

希望有所帮助

<?php
class affiliate{

  // fields or properties
  public $name = '';
  public $id = 0;

  // constructor
  public function affiliate($id = 0){
     $this->set_ID($id);
  }

  // methods
  public function set_ID($id){
    return $this->id = $id;
  }

  public function get_Name(){

    if($this->name != ""){
      $sql = 'SELECT * FROM affiliates WHERE uID="' . $this->id . '" ';
      $res = mysql_query($sql);
      $row = mysql_fetch_array($res);
      return $this->name = $row['firstName'] . ' ' . $row['lastName'];
    }else{
      return $this->name;
    }
  }
}

// Example:

  $currentAffiliate = new affiliate(153);
  echo $currentAffiliate->name;
?>

答案 2 :(得分:1)

我更喜欢以下设计,因为它最简单易用:

class affiliates {
    static function load($id) {
        return new self(intval($id));
    }
    private function __construct($id) {
        $query = "SELECT * FROM affiliates WHERE id = " . intval($id);
        $result = mysql_query($query);
        // TODO: make sure query worked
        foreach(mysql_fetch_assoc($result) as $field => $value)
            $this->$field = $value;
    }
    // composite fields - made by combining and/or re-formatting other fields
    function qualifiedName() {
        return $this->firstName . ' ' . $this->lastName;
    }
    function properName() {
        return $this->lastName . ', ' . $this->firstName;
    }
}

$a = affiliates::load(22);
// all db fields are available as properties:
echo $a->id; // 22
echo $a->firstName; // Fred
echo $a->lastName; // Smith
// composite fields are methods
echo $a->qualifiedName(); // Fred Smith
echo $a->properName(); // Smith, Fred
// to get a single field from a particular person
echo affiliates::load(72)->qualifiedName();