PHP 抽象类数组保护属性


PHP Abstract Class Array Protected Properties

我在使用抽象类和OOP方面有点新手,所以请耐心等待。
我正在尝试制作员工和客户的列表,但我在打印 StoreList 类中的对象数组时遇到了一些麻烦,因为它们都受到保护。
我想做的是将storeArray中的值打印成一个漂亮的列表。
现在,它从抽象类的获取中打印出所有内容,使数组过时。
我将在下面包含所有代码,但由于它很长,我想在这里问这个问题。
这是我在索引或 Storelistclass 上var_dump数组时.php它时输出的内容.php

array (size=5)
  0 => 
    object(Employee)[1]
      protected 'userId' => string '1' (length=1)
      protected 'userFirstName' => string 'Joe' (length=3)
      protected 'userLastName' => string 'Longo' (length=5)
      protected 'userTitle' => string 'Employee' (length=8)
  1 => 
    object(Customer)[2]
      protected 'userId' => string '1' (length=1)
      protected 'userFirstName' => string 'Bruce' (length=5)
      protected 'userLastName' => string 'Stark' (length=5)
      protected 'userTitle' => string 'Customer' (length=8)
  2 => 
    object(Customer)[3]
      protected 'userId' => string '2' (length=1)
      protected 'userFirstName' => string 'Tony' (length=4)
      protected 'userLastName' => string 'Wayne' (length=5)
      protected 'userTitle' => string 'Customer' (length=8)
  3 => 
    object(Customer)[4]
      protected 'userId' => string '3' (length=1)
      protected 'userFirstName' => string 'Oliver' (length=6)
      protected 'userLastName' => string 'Wilson' (length=6)
      protected 'userTitle' => string 'Customer' (length=8)
  4 => 
    object(Customer)[5]
      protected 'userId' => string '4' (length=1)
      protected 'userFirstName' => string 'Slade' (length=5)
      protected 'userLastName' => string 'Queen' (length=5)
      protected 'userTitle' => string 'Customer' (length=8)

无论我在哪里尝试使foreach循环通过数组运行,我都会收到错误:无法访问受保护的属性。

foreach($this->storeArray as $data)
{
    echo $data->userFirstName;
}

当我公开用户抽象类中的属性时,它工作得很好,但是 Get 会过时了吧?我应该放弃 Get 并将它们公开,还是有其他方法?
对不起,如果这是一个愚蠢的问题,但我真的试图解决这个问题并且失败了。

任何帮助和提示(也关于更新和删除功能)将不胜感激!

这就是我现在拥有的所有代码。

索引.php:

<?php
include("classes/Userclass.php");
include("classes/Customerclass.php");
include("classes/Employeeclass.php");
include("classes/Storelistclass.php");
$employeeOne = new Employee("1","Joe","Longo","Employee");
$customerOne = new Customer("1","Bruce","Stark","Customer");
$customerTwo = new Customer("2","Tony","Wayne","Customer");
$customerThree = new Customer("3","Oliver","Wilson","Customer");
$customerFour = new Customer("4","Slade","Queen","Customer");
$list = new Storelist($employeeOne);
$list->addCustomer($customerOne);
$list->addCustomer($customerTwo);
$list->addCustomer($customerThree);
$list->addCustomer($customerFour);
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <!--<link href="includes/stylesheet.css" rel="stylesheet" type="text/css"/>-->
    <title>Store List</title>
  </head>
  <body>
<h1>Test Get Customer</h1>
<p>
  <?php
    echo $customerOne->getUserTitle()." #". $customerOne->getUserId() ."'s First name is ". $customerOne->getUserFirstName() ." and Last name is ". $customerOne->getUserLastName() ."<br/>";
    echo $customerTwo->getUserTitle()." #". $customerTwo->getUserId() ."'s First name is ". $customerTwo->getUserFirstName() ." and Last name is ". $customerTwo->getUserLastName() ."<br/>";
  ?>
</p>
<h1>Test Get Employee</h1>
  <p>
  <?php 
    echo $employeeOne->getUserTitle()." #". $employeeOne->getUserId() ."'s First name is ". $employeeOne->getUserFirstName() ." and Last name is ". $employeeOne->getUserLastName() ."<br/>";
  ?>
</p>
  <h1>Storelist Foreach</h1>
    <p>
      <?php
      $listtest = $list->buildList();
      echo $listtest;
      ?>
  </p>

客户类别.php:

class Customer extends User
{
    public function userSayHi()
    {
        return "Hello , could i get some help?";
    }
}

员工类别.php:

<?php
class Employee extends User
{
    public function userSayHi()
    {
        return 'Hello , how may i help u?';
    }   
}

用户类.php

<?php
abstract class User
{
    protected $userId;
    protected $userFirstName;
    protected $userLastName;
    protected $userTitle;
    public function __construct($id, $firstName, $lastName, $title) 
     {
        $this->userId = $id;
        $this->userFirstName = $firstName;
        $this->userLastName = $lastName;
        $this->userTitle = $title;
     }
    //Gets
    public function getUserId()
    {
        return $this->userId;
    }
    public function getUserFirstName()
    {
        return $this->userFirstName;
    }
    public function getUserLastName()
    {
        return $this->userLastName;
    }
    public function getUserTitle()
    {
        return $this->userTitle;
    }

    //Sets
    public function setUserId($uId)
    {
        $this->userId = $uId;
    }
    public function setUserFirstName($ufirstName)
    {
        $this->userFirstName = $ufirstName;
    }
    public function setUserLastName($ulastName)
    {
        $this->userLastName = $ulastName;
    }
    public function setUserTitle($uTitle)
    {
        $this->userTitle = $uTitle;
    }
    public abstract function userSayHi();
}

存储列表类.php

<?php
require_once("Customerclass.php");
require_once("Employeeclass.php");

 class Storelist
 {

    public $storeArray = [];

    public function __construct(Employee $employee)
    {
        array_push($this->storeArray, $employee);
    }

    public function addCustomer(Customer $customer)
    {
        array_push($this->storeArray, $customer);
        //return $this->storeArray;
    }
    public function buildList()
    {

        foreach($this->storeArray as $storeData)
        {
            echo "First Name: ".$storeData->getUserFirstName()."<br/>";
            echo "Last Name: ".$storeData->getUserLastName()."<br/>";
            echo "Is a: ".$storeData->getUserTitle()."<br/>";
            echo "<br/>";
        }
        /*
        //ERROR : Cannot access protected property Employee::$userFirstName 
       foreach($this->storeArray as $storeData)
        {
            echo "First Name: ".$storeData->userFirstName."<br/>";
            echo "Last Name: ".$storeData->userLastName."<br/>";
            echo "Is a: ".$storeData->userTitle."<br/>";
            echo "<br/>";
        }
        */
    }
     public function delete()
     {
     }
     public function update()
     {
     }
 }

解决方案是实际使用您已经不厌其烦地定义的getter方法(getUserWhatever())。 通过保持它们protected可见性,除了使用您定义的setUserWhatever()方法之外,无法修改它们,因此您可以执行其他验证(例如防止非空值)并对无效数据引发异常。 因此,它们不像public属性那样可以直接从类外部可变,这是很有用的。

Storelist 类中,您已经定义了具有public可见性的 $storeArray 属性,这意味着您可以在 index.php 中读取它在类外部。 由于您要向该数组添加EmployeeCustomer对象,因此这些对象仍可通过其在 $list->storeArray 上的数组键单独寻址。 因此,例如要修改姓氏,您可以使用

// Set the 3rd user's last name
$list->storeArray[2]->setUserLastName('Jones');

同样,在 Storelist 类中使用 $this 也可以这样做:

// Inside Storelist
$this->storeArray[2]->setUserLastName('Jones');

因此,您已经对这些类的布局进行了基本了解。 我还可以建议一件事;由于您已经创建了方法来使用方法调用添加CustomerEmployee对象以Storelist::$storeArray,而不是直接修改数组:

// You're doing this:
$list = new Storelist($employeeOne);
$list->addCustomer($customerOne);
// And not this (directly modifying storeArray):
$list = new Storelist($employeeOne);
$list->storeArray[] = $customerOne

。然后,还考虑将 Storelist::$storeArray 定义为 protected 属性,以便只能使用其 setter 方法写入它。然后,您还需要创建一个返回数组的 getter 方法。

class Storelist
{
    // This becomes protected
    protected $storeArray = [];
    // So you need a getter:
    public function getStoreArray()
    {
       return $this->storeArray;
    }
    // etc...
}

要从index.php修改数组,则无法再直接读取其元素。相反,你称之为getter方法:

// You can't do this:
$list->storeArray[2]->setUserLastName('Jones');
// Instead do it via the getter:
$list->getStoreArray()[2]->setUserLastName('Jones');

(注意,上面的()[2]语法需要 PHP 5.4+)