Php must be callable array given

PHP Type hinting Type hinting scalar types, arrays and callables

Support for type hinting array parameters (and return values after PHP 7.1) was added in PHP 5.1 with the keyword array . Any arrays of any dimensions and types, as well as empty arrays, are valid values.

Support for type hinting callables was added in PHP 5.4. Any value that is_callable() is valid for parameters and return values hinted callable , i.e. Closure objects, function name strings and array(class_name|object, method_name) .

If a typo occurs in the function name such that it is not is_callable() , a less obvious error message would be displayed:

Fatal error: Uncaught TypeError: Argument 1 passed to foo() must be of the type callable, string/array given

function foo(callable $c) <> foo("count"); // valid foo("Phar::running"); // valid foo(["Phar", "running"); // valid foo([new ReflectionClass("stdClass"), "getName"]); // valid foo(function() <>); // valid foo("no_such_function"); // callable expected, string given 

Nonstatic methods can also be passed as callables in static format, resulting in a deprecation warning and level E_STRICT error in PHP 7 and 5 respectively.

Читайте также:  Найти квадрат числа python

Method visibility is taken into account. If the context of the method with the callable parameter does not have access to the callable provided, it will end up as if the method does not exist.

class Foo < private static function f()< echo "Good" . PHP_EOL; >public static function r(callable $c) < $c(); >> function r(callable $c)<> Foo::r(["Foo", "f"]); r(["Foo", "f"]); 

Fatal error: Uncaught TypeError: Argument 1 passed to r() must be callable, array given

Support for type hinting scalar types was added in PHP 7. This means that we gain type hinting support for boolean s, integer s, float s and string s.

 var_dump(add(1, 2)); // Outputs "int(3)" 

By default, PHP will attempt to cast any provided argument to match its type hint. Changing the call to add(1.5, 2) gives exactly the same output, since the float 1.5 was cast to int by PHP.

To stop this behavior, one must add declare(strict_types=1); to the top of every PHP source file that requires it.

The above script now produces a fatal error:

Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, float given

An Exception: Special Types

Some PHP functions may return a value of type resource . Since this is not a scalar type, but a special type, it is not possible to type hint it.

As an example, curl_init() will return a resource , as well as fopen() . Of course, those two resources aren’t compatible to each other. Because of that, PHP 7 will always throw the following TypeError when type hinting resource explicitly:

TypeError: Argument 1 passed to sample() must be an instance of resource, resource given

pdf

PDF — Download PHP for free

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better error messages for type callable #8039

Better error messages for type callable #8039

Comments

Description

I deliberately avoid the callable type in my code because it produces misleading error messages.

$cb = [PhpTokn::class, 'tokenize']; // typo in class name (fn(callable $cb) => 0)($cb); // expected error: Argument #1 ($cb) must be of type callable, but class "PhpTokn" does not exist // actual error: Argument #1 ($cb) must be of type callable, array given 
$cb = [PhpToken::class, 'tokenze']; // typo in method name (fn(callable $cb) => 0)($cb); // expected error: Argument #1 ($cb) must be of type callable, but method PhpToken::tokenze() does not exist // actual error: Argument #1 ($cb) must be of type callable, array given 
$cb = 'PhpTokn::tokenize'; // typo in class name (fn(callable $cb) => 0)($cb); // expected error: Argument #1 ($cb) must be of type callable, but class "PhpTokn" does not exist // actual error: Argument #1 ($cb) must be of type callable, string given 
$cb = 'PhpToken::tokenze'; // typo in method name (fn(callable $cb) => 0)($cb); // expected error: Argument #1 ($cb) must be of type callable, but method PhpToken::tokenze() does not exist // actual error: Argument #1 ($cb) must be of type callable, string given 

Not only does the error message not tell you exactly what is wrong with the callback, but it is also little misleading. Message Must be callable, array given suggests, that something other than array (or string) was expected.

Thanks for your consideration.

The text was updated successfully, but these errors were encountered:

Источник

Php – Argument passed to function must be callable, array given

I’m trying to run a method on each element inside a collection. It’s an object method residing in the same class:

protected function doSomething() < $discoveries = $this->findSomething(); $discoveries->each([$this, 'doSomethingElse']); > protected function doSomethingElse($element) < $element->bar(); // And some more > 

If I precede the call on Collection::each with the check is_callable([$this, ‘doSomethingElse’]) it returns true, so apparently it is callable. The call itself however throws an exception:

Type error: Argument 1 passed to Illuminate\Support\Collection::each() must
be callable, array given, called in —.php on line 46

The method trying to be called can be found here.

I’m bypassing this by just passing a closure that itself simply calls that function, but this would definitely a much cleaner solution and I can’t find out why it throws the error.

Best Solution

Change the visibility of your callback method to public.

protected function doSomething() < $discoveries = $this->findSomething(); $discoveries->each([$this, 'doSomethingElse']); > public function doSomethingElse($element) < $element->bar(); // And some more > 
Php – Reference – What does this error mean in PHP

Warning: Cannot modify header information — headers already sent

Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.

This is an E_WARNING and it will not stop the script.

A typical example would be a template file like this:

The session_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the element to the output stream. You’d have to move the session_start() to the top.

You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.

An often overlooked output is new lines after PHP’s closing ?> . It is considered a standard practice to omit ?> when it is the last thing in the file. Likewise, another common cause for this warning is when the opening

If your file has more than one code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)

Also make sure you don’t have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.

Java – Ways to iterate over a list in Java

The three forms of looping are nearly identical. The enhanced for loop:

is, according to the Java Language Specification, identical in effect to the explicit use of an iterator with a traditional for loop. In the third case, you can only modify the list contents by removing the current element and, then, only if you do it through the remove method of the iterator itself. With index-based iteration, you are free to modify the list in any way. However, adding or removing elements that come before the current index risks having your loop skipping elements or processing the same element multiple times; you need to adjust the loop index properly when you make such changes.

In all cases, element is a reference to the actual list element. None of the iteration methods makes a copy of anything in the list. Changes to the internal state of element will always be seen in the internal state of the corresponding element on the list.

Essentially, there are only two ways to iterate over a list: by using an index or by using an iterator. The enhanced for loop is just a syntactic shortcut introduced in Java 5 to avoid the tedium of explicitly defining an iterator. For both styles, you can come up with essentially trivial variations using for , while or do while blocks, but they all boil down to the same thing (or, rather, two things).

EDIT: As @iX3 points out in a comment, you can use a ListIterator to set the current element of a list as you are iterating. You would need to use List#listIterator() instead of List#iterator() to initialize the loop variable (which, obviously, would have to be declared a ListIterator rather than an Iterator ).

Related Question

Источник

Ошибка в модуле iblock

Есть BitrixVM 7.5
На нем установлен чистый Битрикс УС Бизнес и дополнительно установлен модуль «Продажа контента»
В этом модуле есть функционал добавления ключей, но при нажатии кнопки: «Продукт ключа» получаю ошибку в модуле iblock:

[TypeError] Argument 1 passed to Bitrix\Main\Loader::registerHandler() must be callable, array given, called in /home/bitrix/www/bitrix/modules/iblock/autoload.php on line 155 (0) /home/bitrix/www/bitrix/modules/main/lib/loader.php:327 #0: Bitrix\Main\Loader::registerHandler /home/bitrix/www/bitrix/modules/iblock/autoload.php:155 #1: require_once(string) /home/bitrix/www/bitrix/modules/iblock/iblock.php:11 #2: require_once(string) /home/bitrix/www/bitrix/modules/asd.isale/admin/isale_element_search.php:3 #3: require(string) /home/bitrix/www/bitrix/admin/isale_element_search.php:1

Рискну предположить, что в этой строке вместо CModule::IncludeModule или \Bitrix\Main\Loader::includeModule стоит подключение файла bitrix/modules/iblock/include.php

Цитата
Рискну предположить, что в этой строке вместо CModule::IncludeModule или \Bitrix\Main\Loader::includeModule стоит подключение файла bitrix/modules/iblock/include.php
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/iblock/iblock.php");
\Bitrix\Main\Loader::includeModule('iblock');

Продукты

Управление сайтом

Битрикс24

Интернет-магазин + CRM

Решения

Для интернет-магазинов

Каталог готовых решений

Внедрение

Выбрать партнера

Проверить партнера

Стать партнером

1С-Битрикс http://www.1c-bitrix.ru Общие вопросы info@1c-bitrix.ru Приобретение и лицензирование продуктов : sales@1c-bitrix.ru Маркетинг/мероприятия/PR marketing@1c-bitrix.ru Партнерская программа partners@1c-bitrix.ru Мы работаем с 10:00 до 19:00 по московскому времени. Офис в Москве 127287 Россия Московская область Москва 2-я Хуторская улица дом 38А строение 9 Офис в Калининграде +7 (4012) 51-05-64 Офис в Калининграде 236001 Россия Калининградская область Калининград Московский проспект 261 Офис в Киеве ukraine@1c-bitrix.ru Телефон в Киеве +3 (8044)221-55-33 Офис в Киеве 01033 Украина Калининградская область Киев улица Шота Руставели 39/41 офис 1507

Контент для лиц от 16 лет и старше

© 2001-2023 «Битрикс», «1С-Битрикс». Работает на 1С-Битрикс: Управление сайтом. Политика конфиденциальности

Источник

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