PHP抽象类数组受保护的属性

时间:2015-01-30 17:10:09

标签: php arrays oop properties abstract-class

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

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;
}

当我在User抽象类中公开属性时,它工作正常,但是然后获取会过时吗? 我应该放弃获取并将它们公之于众,还是有另一种方式? 对不起,如果这是一个有点愚蠢的问题,但我真的试图围绕这个并且没有做到这一点。

任何帮助和提示(还有关于更新和删除功能)将非常感谢!

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

的index.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>

Customerclass.php:

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

Employeeclass.php:

<?php

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

Userclass.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();
}

Storelistclass.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()
     {

     }
 }

1 个答案:

答案 0 :(得分:0)

解决方案是实际使用你已经遇到定义麻烦的getter方法(getUserWhatever())。通过使用protected可见性保持原样,除了使用您定义的setUserWhatever()方法之外,无法修改它们,因此您可以执行其他验证(例如防止非空值)例如,在无效数据上抛出异常。因此有用的是,它们不能直接从类外部变为public属性。

Storelist课程中,您已将$storeArray属性定义为public,这意味着您可以在index.php的课程外读取该属性。由于您要向该数组添加EmployeeCustomer个对象,因此这些对象仍可通过$list->storeArray上的数组键单独寻址。因此,要修改姓氏,您可以使用

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

同样,使用$this类中的Storelist也是可以的:

// 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 +)