/ LJCPHPCodeDoc / LJCCollectionLib / LJCCollectionBase / AddItem


Parameters
$item - The object to be added to the collection.
$key - The element key.

Returns

The added item.

Syntax

PHP
protected function AddItem($item, $key = null)

Adds an object and key value.

Example

PHP
 // The data object class.
 class Name
 {
   public string $Name;
 }
 
 // The strongly typed collection class.
 class Names Extends LJCCollectionBase
 {
   // Adds an object and key value.
   // This method makes a collection strongly typed.
   // The key defaults to a unique object property.
   public function AddObject(Name $item, $key = null): Name
   {
     $retItem = $item;
 
     if ($item != null)
     {
       if (null == $key
         && property_exists($item, "Name")
         && $item->Name != null
         && strlen(trim($item->Name)) > 0)
       {
         $key = $item->Name;
       }
       $retItem = $this->AddItem($item, $key);
     }
     return $retItem;
   }
 }
 
 // Add to class that extends LJCCollectionBase
 // Adds an object and key value.
 public function AddObject(Name $item, $key = null)
 {
   $names = new Names();
   $name = new Name();
   $name->Name = "One";
   $names->AddObject($name);
   $item = $names->Retrieve("One");
   $result = $item->Name;
 
   // result:
   // One
 }

Copyright © Lester J. Clark and Contributors.
Licensed under the MIT License.