[英]Accessing class properties in PHP OOP
我是 PHP OOP 新手,想知道是否有人可以帮助我。
我有一个带有从数据库返回数据的方法的基本类。 目前我正在调用显示函数内所有内容的方法。
这是我的类定义:
class Products{
//properties
public $familyName = "";
public $familyProduct = "";
//Methods
public function getFamily($catId){
global $conn;
$sql = "SELECT * FROM product_family WHERE catID = '$catId'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<li>".$row['familyName']."</li>";
echo "<li>".$row['familyProduct']."</li>";
}
}
}
}
这是我调用该方法的方式:
$Products = new Products;
$Products->getFamily( 4 );
但是,这是有效的,我如何将来自数据库(ex familyName,familyProduct)的每个数据分配到类实现中的变量中,然后在需要的地方单独访问它们。 像这样的东西:
$Products = new Products;
$Products->familyName;
$Products->familyProduct;
我有空属性,但我不确定如何为来自循环的它们分配值,然后每个返回它们。
谢谢,
我会在您的代码中更改某些视图。
不要让属性公开使用使用 Getter 和 Setter。
这将保护您的对象不会被错误地使用,例如现在您不能从外部更改familyName
: $products->familyName = "some value"
因为这会使对象的数据损坏。
global $conn;
在 OOP 中不能使用对象的构造,
在你的情况下$products = new Products($conn);
现在你可以设置一个猫 ID $products->setCatId(4);
并读取结果$familyName = $products->getFamilyName();
或$familyProduct = $products->getFamilyProduct();
如果你有多个结果,你会得到一个数组,如果 catId 总是产生一行,你可以删除这部分。 如果您了解更多有关 OOP 的信息,您会发现可以使用单独的对象来完成空洞 SQL 的工作,但这与主题无关。
class Products
{
// Properties
protected $conn;
protected $catId;
protected $familyName;
protected $familyProduct;
public function __construct($conn)
{
$this->conn = $conn;
}
// set Cat ID and get date
public function setCatId($catId)
{
$this->catId = (int) $catId;
$this->getDate();
}
public function getCatId()
{
return $this->catId;
}
// get Family Name
public function getFamilyName()
{
return $this->familyName;
}
// get Family Product
public function getFamilyProduct()
{
return $this->familyProduct;
}
// get date
protected function getDate()
{
$sql = "SELECT * FROM product_family WHERE catID = '$this->catId'";
$result = $this->conn->query($sql);
// Default if no result
$this->familyName = null;
$this->familyProduct = null;
// if one Result
if ($result->num_rows == 1)
{
$row = $result->fetch_assoc();
$this->familyName = $row['familyName'];
$this->familyProduct = $row['familyProduct'];
}
if ($result->num_rows > 1)
{
$this->familyName = [];
$this->familyProduct = [];
while ($row = $result->fetch_assoc())
{
$this->familyName[] = $row['familyName'];
$this->familyProduct[] = $row['familyProduct'];
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.