Php count class objects

count

Подсчитывает количество элементов массива или что-то в объекте.

Для объектов, если у вас включена поддержка SPL, вы можете перехватить count() , реализуя интерфейс Countable. Этот интерфейс имеет ровно один метод, Countable::count() , который возвращает значение функции count() .

Пожалуйста, смотрите раздел «Массивы» в этом руководстве для более детального представления о реализации и использовании массивов в PHP.

Список параметров

Если необязательный параметр mode установлен в COUNT_RECURSIVE (или 1), count() будет рекурсивно подсчитывать количество элементов массива. Это особенно полезно для подсчёта всех элементов многомерных массивов.

count() умеет определять рекурсию для избежания бесконечного цикла, но при каждом обнаружении выводит ошибку уровня E_WARNING (в случае, если массив содержит себя более одного раза) и возвращает большее количество, чем могло бы ожидаться.

Возвращаемые значения

Возвращает количество элементов в array_or_countable . Если параметр не является массивом или объектом, реализующим интерфейс Countable, будет возвращена 1. За одним исключением: если array_or_countable — NULL , то будет возвращён 0.

count() может возвратить 0 для переменных, которые не установлены, но также может возвратить 0 для переменных, которые инициализированы пустым массивом. Используйте функцию isset() для того, чтобы протестировать, установлена ли переменная.

Примеры

Пример #1 Пример использования count()

$a [ 0 ] = 1 ;
$a [ 1 ] = 3 ;
$a [ 2 ] = 5 ;
$result = count ( $a );
// $result == 3

$b [ 0 ] = 7 ;
$b [ 5 ] = 9 ;
$b [ 10 ] = 11 ;
$result = count ( $b );
// $result == 3

$result = count ( null );
// $result == 0

$result = count ( false );
// $result == 1
?>

Пример #2 Пример рекурсивного использования count()

$food = array( ‘fruits’ => array( ‘orange’ , ‘banana’ , ‘apple’ ),
‘veggie’ => array( ‘carrot’ , ‘collard’ , ‘pea’ ));

// рекурсивный count
echo count ( $food , COUNT_RECURSIVE ); // выводит 8

// обычный count
echo count ( $food ); // выводит 2

Смотрите также

  • is_array() — Определяет, является ли переменная массивом
  • isset() — Определяет, была ли установлена переменная значением отличным от NULL
  • strlen() — Возвращает длину строки

Источник

PHP RFC: instance counter

Coming to Object-Orientated Programming, PHP offers a variety of possibilities to obtain information about classes and their instances (objects). In this regard, the classes/objects functions (http://www.php.net/manual/en/ref.classobj.php) as well as the reflection API (http://www.php.net/manual/en/book.reflection.php) do a great job. But still there is no function to obtain a particular information: the number of instances of a class.

One might say, simply implement a static counter in each class. But what about built-in classes like SPL? A wrapper would be required. Implementing it these ways, it not only sounds, but actually is cumbersome. The purpose of this RFC is to address this issue.

Читайте также:  Xampp как установить php

Proposal

The proposal is to add a new functionality dealing with the number of instances of either a specific class name/object or set of class names/objects or all classes.

The function name should fit in with the current names of class/object functions. Therefore, the name get_objects_count() seems to be reasonable.

If no argument is provided, the number of all objects in the object store as an associative array (‘class name’ => count) will be returned.

print_r (get_objects_count()); // Array () $foo = new stdClass; print_r (get_objects_count()); // Array ( [stdClass] => 1 ) $bar = new stdClass; print_r (get_objects_count()); // Array ( [stdClass] => 2 ) $bar = null; print_r (get_objects_count()); // Array ( [stdClass] => 1 ) $foo = null; print_r (get_objects_count()); // Array ()

If a class name is provided, the number of objects of the specified class in the object store will be returned.

print get_objects_count('stdClass'); // 0 $foo = new stdClass; print get_objects_count('stdClass'); // 1 $bar = new stdClass; print get_objects_count('stdClass'); // 2 $bar = null; print get_objects_count('stdClass'); // 1 $foo = null; print get_objects_count('stdClass'); // 0

If an object is provided, the number of objects of the specifiied objects class in the object store will be returned. The return value is always ≥ 1.

$foo = new stdClass; print get_objects_count($foo); // 1 $bar = new stdClass; print get_objects_count($bar); // 2 $bar = null; print get_objects_count($foo); // 1

If an an array is provided, it will be the treated as an inclusive indexed array of class names. An associative array (‘class name’ => count) will be returned.

print_r (get_objects_count(array('stdClass'))); // Array ( [stdClass] => 0 ) $foo = new stdClass; print_r (get_objects_count(array('stdClass'))); // Array ( [stdClass] => 1 ) $bar = new stdClass; print_r (get_objects_count(array('stdClass'))); // Array ( [stdClass] => 2 ) $bar = null; print_r (get_objects_count(array('stdClass'))); // Array ( [stdClass] => 1 ) $foo = null; print_r (get_objects_count(array('stdClass'))); // Array ( [stdClass] => 0 )

General questions & answers

Inheritance

On internals list there was the question, if only the “direct” instances of a class or also the instances of subclasses are counted? The answer is: only direct instances. See the following code:

class A {} class B extends A {} print get_objects_count('A'); // 0 $b = new B; var_dump($b instanceof A); // bool(true) print get_objects_count('A'); // 0 print get_objects_count('B'); // 1

Источник

How to Count the Number of Objects in a Class in PHP

In this article, we go over how to count the number of objects in a class in PHP.

Every time we instantiate (create) a new object, we can keep track of this through a static property. Thus, we can count the number of objects instantiated for a given class.

As far as I know, PHP does not have a built-in function that counts the number of objects in a class, so we simply create a custom one and it’s very easy to do.

We create a static property (since it isn’t tied to an object but to the class) and we put inside of the constructor. Since the constructor is called every time that an object is instantiated, we add increment the static property keeping count by 1 each time an object is instantiated, we can keep track of the number of objects in a class.

Читайте также:  Javascript передать значение select

So in the PHP code below, we have created a program that counts the number of objects created for a class in PHP.

So in this code, we create a class named cars.

We declare a public static property named $count and we set it equal to 0. This variable will be used to count the number of objects created in a class.

We then create the constructor for the class. Since this is a class that represents cars, each object created is a car object (represents a car). We want to pass into the car objects the type and year of the car.

So in the constructor, we pass in the arguments $type and $year, representing the type and year of the car.

We then use the $this keyword to assign the value of the type and year to the $type and $year variables.

We then use the increment operator to increment the cars::$count property.

Because the constructor is called each time an object is created, we can use this fact to keep track of how many objects are created. Initially, the cars::$count variable is 0. However, with each object that is instantiated, the count goes up by 1. Thus, we’re able to know how many objects have been created.

Since we’ve created 5 cars, at the end of this program, you’ll see that the program says there are 5 objects created.

Actual PHP Output

The number of objects in the class is 5

Keeping Count of the Number of Objects If Any Are Deleted

You could make this program a little more elaborate.

For example, what if an object is destroyed? What if we delete one or more of the objects after they are created?

In that case, you would also have to make a destructor function for the class. When an object is destroyed (if you unset an object) then you place in the destructor function, a decrement operator for the cars::$count variable. So if an object is destroyed, the count goes down by 1. This way, you can keep track of how many objects currently exist for a class.

So below is the code that keeps track of all currently existing objects in a class. If an object is created, the count goes up by 1. If an object is destroyed, the count goes down by 1.

So all the code is mostly the same except now we have a class destructor and we intentionally delete an object, $car4. Inside of the destructor, we have the cars::$count variable decrementing by 1 each time the destructor is called. And the destructor function is called when we delete an object through the PHP unset() function. So whenever we delete an object, the count goes down by 1.

So now when we run our code, now that we’ve deleted one of the objects, the count will be 4.

Читайте также:  Создание градиента в html

So if I run the PHP code above, we get the following output below.

Actual PHP Output

The number of objects in the class is 4

So using a static variable is a very effective and easy way to keep track of the number of objects in a class.

Because a static variable isn’t tied to an object and is instead tied to a class, it is independent of any object in the class. Therefore, it has an outsider view, so to speak, and can keep track of all objects in a class.

So this is how you can keep track of the number of objects in a class in PHP.

Источник

PHP: Count a Stdclass Object

The problem is that count is intended to count the indexes in an array, not the properties on an object, (unless it’s a custom object that implements the Countable interface). Try casting the object, like below, as an array and seeing if that helps.

Simply casting an object as an array won’t always work but being a simple stdClass object it should get the job done here.

count of stdClass objects Array in php

I have solved my question by following way:

foreach ($offers as $key=> $value) 
echo "
count->".count($value);
>

this loops itreate only once, and give me result.

Count Objects in PHP

From your example, using objects for this seems a very bloated method. Using a simple array would be much easier and faster.

object(stdClass)#46 (3) ["0"]=> 
object(stdClass)#47 (1) ["productid"]=>
string(2) "15"
>
>

Your example only seems to be storing a product id, so you don’t strictly need a key of «productid»

Is there any specific reason you need to use objects?

PHP: Count number of objects within another object?

PHP: Count a stdClass object

The problem is that count is intended to count the indexes in an array, not the properties on an object, (unless it’s a custom object that implements the Countable interface). Try casting the object, like below, as an array and seeing if that helps.

Simply casting an object as an array won’t always work but being a simple stdClass object it should get the job done here.

Why does `count(new stdClass);` return 1?

If you read the documentation of the count function, you’ll find this section about the return value:

Return Values

Returns the number of elements in array_or_countable. If the parameter
is not an array or not an object with implemented Countable interface,
1 will be returned. There is one exception, if array_or_countable is
NULL, 0 will be returned.

Get data from stdclass Object — Count from mysql

You have made life a little difficult for yourself by not giving the result column a nice easily accessible name

If you change your query so the column has a known name like this

$park = $wpdb->get_row("SELECT COUNT(1) as count 
FROM wp_richreviews
WHERE review_status='1'");

then you have a nice easily accessible property called count

Источник

Оцените статью