3

In a variable of $order->items I have the output below. I have removed the contents of the arrays to make it easier to view.

How can I count the arrays? The example would output 3.

I am unfamiliar with objects and protected elements.

Store\Model\Collection Object ( [items:protected] => 

Array ( 

    [0] => Store\Model\OrderItem Object ( ... ) 

    [1] => Store\Model\OrderItem Object ( ... ) 

    [2] => Store\Model\OrderItem Object ( ... )

)

2 Answers 2

2

If class Store\Model\Collection implements Countable interface, you can just get count through count($object);.

Otherwise add method that returns array size

class Store\Model\Collection
{
    protected $items;
    ....
    public function getItemsCount()
    {
        return count($this->items);
    }
}

and use it in application as

$object->getItemsCount();
Sign up to request clarification or add additional context in comments.

Comments

0

You can't access directly to protected attributes of an object. You must add to your Store\Model\Collection class a function to get your Array or a function to count items into your array.

<?php

class Obj{
    $name = "";
    public function __construct($name){
        $this->name = $name
    }
}

class Collection{
    protected $items = [
        new Obj("toto"),
        new Obj("tata"),
        new Obj("tutu")
    ]

    public function getItems(){
        return $this->items;
    }

    public function countItems(){
        return count($this->items);
    }
}

?>

Protected attributes or protected functions are only accessible within the class or classes which inherit of. So you must have public functions to access this attributes or functions outside of the class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.