I'm new to object oriented programming in PHP. I made a simple order class with an array property. The method orderLength is not working. I'm getting an error:
Call to undefined method Order::count()
PHP:
<?php
class Order {
private $order = array();
public function setOrder($wert) {
foreach($wert as $value) {
$this -> order[] = $value;
}
}
public function orderLength() {
$length = $this -> count(order);
return $length;
}
public function returnOrder() {
$value = $this -> order;
return $value;
}
}
$order = new Order;
$order -> setOrder(array('Book1', 'Book2', 'Book3', 'Book4'));
foreach ($order->returnOrder() as $value) {
echo $value . " <br/>";
}
echo "The order length is: " . $order->orderLength();
You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.
The count() function is used to count the elements of an array or the properties of an object. Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.
If you want to find the length of an array in PHP, you can use the sizeof function and use the echo command along with it to print the length. The second method is using a function called: count().
Instead of $this->count(order)
you can try with:
$length = count($this->order);
Just return the count of $order:
public function orderLength() {
return count($this->order);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With