Пример запроса (первая клетка). System одинаковый во всех запросах прогона, user — свой вопрос для каждой клетки:
| Клетка | Тема | Утверждение | Ответ |
Результат | Обоснование |
T01-L1 3.12 c | Syntax and operators | Double-quoted and single-quoted strings are processed identically; the difference is only in speed. | «no» Пояснение: Double-quoted strings support variable interpolation and escape sequences, while single-quoted strings do not, so they are not processed identically.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "Double-quoted strings support variable interpolation and escape sequences, while single-quoted strings do not, so they are not processed identically." ⏎ } | верно | В двойных кавычках работают интерполяция переменных и escape-последовательности, в одинарных — нет. |
T01-L2 0.29 c | Syntax and operators | The ?? operator follows isset semantics and raises no warnings for undefined variables. | «yes» Пояснение: The null coalescing operator (??) suppresses notices for undefined indices or variables, similar to isset().
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "The null coalescing operator (??) suppresses notices for undefined indices or variables, similar to isset()." ⏎ } | верно | ?? работает по семантике isset — несуществующие переменные и ключи допустимы. |
T01-L3 0.39 c | Syntax and operators | What will this print: echo 'a', 'b'; | «ab» Пояснение: In PHP, using the comma (,) as a separator in an echo statement concatenates the strings 'a' and 'b', resulting in 'ab'.
Raw{"answer": "ab", "explanation": "In PHP, using the comma (,) as a separator in an echo statement concatenates the strings 'a' and 'b', resulting in 'ab'."} | верно | echo принимает список аргументов: ab. |
T01-L4 1.81 c | Syntax and operators | print returns the value 1 and can be used inside an expression. | «no» Пояснение: In PHP, print is a language construct that returns 1 (the integer) as a status code, but it is not designed to be used as a function inside expressions (unlike echo, which returns nothing but is also not a function; however, print does return 1 but is often treated as a statement rather than an expression-friendly function in strict terms, though technically you can use it inside expressions since it returns a value. But the common and correct interpretation is that print returns 1 but echo returns nothing; both are statements, not functions, and using print inside expressions is allowed but not recommended. The statement says 'can be used inside an expression' which is technically true since it returns a value, but the conventional answer in such quizzes is false because it's not a function and its use in expressions is uncommon and discouraged. So, the expected answer is no/false.)
Raw```json ⏎ {"answer": "no", "explanation": "In PHP, print is a language construct that returns 1 (the integer) as a status code, but it is not designed to be used as a function inside expressions (unlike echo, which returns nothing but is also not a function; however, print does return 1 but is often treated as a statement rather than an expression-friendly function in strict terms, though technically you can use it inside expressions since it returns a value. But the common and correct interpretation is that print returns 1 but echo returns nothing; both are statements, not functions, and using print inside expressions is allowed but not recommended. The statement says 'can be used inside an expression' which is technically true since it returns a value, but the conventional answer in such quizzes is false because it's not a function and its use in expressions is uncommon and discouraged. So, the expected answer is no/false.)"} ⏎ ``` | неверно верный: «yes» | print — выражение со значением 1, в отличие от echo, который значения не возвращает. |
T01-L5 0.33 c | Syntax and operators | The ?: (elvis) operator returns its left operand when it is falsy. | «no» Пояснение: The Elvis operator (?:) returns the left operand when it is truthy, not falsy.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "The Elvis operator (?:) returns the left operand when it is truthy, not falsy." ⏎ } | верно | Наоборот: $a ?: $b возвращает $a, если он истинный, иначе $b. |
T01-L6 0.51 c | Syntax and operators | In PHP 8, the concatenation operator (.) has lower precedence than addition and subtraction. | «yes» Пояснение: In PHP, arithmetic operators like + and - have higher precedence than the concatenation operator ., meaning expressions like 1 + 1 . '2' evaluate as (1 + 1) . '2' resulting in '22'.
Raw{"answer": "yes", "explanation": "In PHP, arithmetic operators like + and - have higher precedence than the concatenation operator ., meaning expressions like 1 + 1 . '2' evaluate as (1 + 1) . '2' resulting in '22'."} | верно | С PHP 8 (RFC concat precedence) '.' имеет приоритет ниже арифметики: 'сумма: ' . 2 + 3 → 'сумма: 5' (в PHP 7 было иначе). |
T01-L7 0.43 c | Syntax and operators | The expression 2 ** 3 ** 2 in PHP evaluates as (2 ** 3) ** 2, that is, 64. | «no» Пояснение: The exponentiation operator ** in PHP is right-associative, so 2 ** 3 ** 2 evaluates as 2 ** (3 ** 2), which is 2 ** 9 = 512.
Raw{"answer": "no", "explanation": "The exponentiation operator ** in PHP is right-associative, so 2 ** 3 ** 2 evaluates as 2 ** (3 ** 2), which is 2 ** 9 = 512."} | верно | ** право-ассоциативен: 2 ** (3 ** 2) = 2 ** 9 = 512. |
T01-L8 0.42 c | Syntax and operators | What string will this print: echo 'sum: ' . 2 + 3; (PHP 8)? | «sum: 5» Пояснение: In PHP, the concatenation operator . has lower precedence than the addition operator +, so 'sum: ' . (2 + 3) is evaluated, resulting in 'sum: 5'.
Raw{"answer": "sum: 5", "explanation": "In PHP, the concatenation operator . has lower precedence than the addition operator +, so 'sum: ' . (2 + 3) is evaluated, resulting in 'sum: 5'."} | верно | Парная к verify-клетке про приоритет: 'сумма: 5'. |
T02-L1 0.3 c | Types and comparisons | With strict comparison (===), arrays are considered equal regardless of element order. | «no» Пояснение: With strict comparison (===), arrays must have the same key-value pairs in the same order to be considered equal.
Raw{"answer": "no", "explanation": "With strict comparison (===), arrays must have the same key-value pairs in the same order to be considered equal."} | верно | === для массивов требует совпадения и значений, и их порядка. |
T02-L2 0.4 c | Types and comparisons | The comparison 0 == false returns false because it is a strict comparison. | «no» Пояснение: The comparison '0 == false' uses the non-strict equality operator ('=='), and in PHP, 0 and false are considered equal.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "The comparison '0 == false' uses the non-strict equality operator ('=='), and in PHP, 0 and false are considered equal." ⏎ } ⏎ ``` | верно | Наоборот: == — нестрогое сравнение и возвращает true; строгое — это === (0 === false → false). |
T02-L3 0.39 c | Types and comparisons | In PHP 8, the expression "abc" == 0 returns true. | «yes» Пояснение: In PHP 8, comparing a non-numeric string to an integer uses the same logic as PHP 7, so 'abc' == 0 is true.
Raw```json ⏎ {"answer": "yes", "explanation": "In PHP 8, comparing a non-numeric string to an integer uses the same logic as PHP 7, so 'abc' == 0 is true."} ⏎ ``` | неверно верный: «no» | С PHP 8 нечисловая строка сравнивается как строка: "abc" == "0" → false (в PHP 7 было true). |
T02-L4 0.53 c | Types and comparisons | Under loose comparison, null equals 0, the empty string, and false at the same time. | «no» Пояснение: In PHP 8+, null is only loosely equal to false; in PHP 7 and earlier, it was equal to 0 and the empty string as well, so the statement is only true under older versions.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "In PHP 8+, null is only loosely equal to false; in PHP 7 and earlier, it was equal to 0 and the empty string as well, so the statement is only true under older versions." ⏎ } | неверно верный: «yes» | null == 0, null == "" и null == false — все true. |
T02-L5 0.36 c | Types and comparisons | What does the expression (int) '42abc' return? | «42» Пояснение: In PHP, casting a string to int stops at the first non-numeric character, so '42abc' becomes 42.
Raw{"answer": 42, "explanation": "In PHP, casting a string to int stops at the first non-numeric character, so '42abc' becomes 42."} | верно | Ведущая числовая часть: 42, без ошибок и warning. |
T02-L6 0.35 c | Types and comparisons | What does the expression '5' + 5 return? | «10» Пояснение: PHP casts the string '5' to an integer 5 because it looks like a number, then adds 5.
Raw{"answer": 10, "explanation": "PHP casts the string '5' to an integer 5 because it looks like a number, then adds 5."} | верно | Числовая строка приводится: int 10. |
T02-L7 0.27 c | Types and comparisons | When cast to string, false becomes "0". | «yes» Пояснение: When false is cast to string in PHP, it becomes the string "0".
Raw```json ⏎ {"answer": "yes", "explanation": "When false is cast to string in PHP, it becomes the string \"0\"."} ⏎ ``` | неверно верный: «no» | false → "", true → "1". |
T02-L8 0.43 c | Types and comparisons | The comparison 0.1 + 0.2 === 0.3 returns false. | «yes» Пояснение: In PHP, 0.1 + 0.2 results in a floating-point value that is not exactly equal to 0.3 due to floating-point precision issues, so the strict comparison (===) returns false.
Raw```json ⏎ {"answer": "yes", "explanation": "In PHP, 0.1 + 0.2 results in a floating-point value that is not exactly equal to 0.3 due to floating-point precision issues, so the strict comparison (===) returns false."} ⏎ ``` | верно | Двоичная погрешность float: 0.1 + 0.2 = 0.30000000000000004. |
T03-L1 0.42 c | Strings | strrev() correctly reverses a UTF-8 string. | «no» Пояснение: strrev() operates byte-wise, so it can break multi-byte UTF-8 characters; ustrrev() should be used for proper UTF-8 reversal.
Raw{"answer": "no", "explanation": "strrev() operates byte-wise, so it can break multi-byte UTF-8 characters; ustrrev() should be used for proper UTF-8 reversal."} | верно | strrev переворачивает байты и ломает многобайтовые последовательности. |
T03-L2 0.35 c | Strings | str_contains('Hello world', 'world') returns true. | «yes» Пояснение: The str_contains function checks if a needle string is found in a haystack string, and 'world' is indeed a substring of 'Hello world'.
Raw{"answer": "yes", "explanation": "The str_contains function checks if a needle string is found in a haystack string, and 'world' is indeed a substring of 'Hello world'."} | верно | str_contains с PHP 8.0 проверяет вхождение подстроки. |
T03-L3 0.31 c | Strings | str_pad() can pad a string on the right side only. | «no» Пояснение: str_pad() can pad on the left, right, or both sides using the STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH constants.
Raw{"answer": "no", "explanation": "str_pad() can pad on the left, right, or both sides using the STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH constants."} | верно | STR_PAD_LEFT / STR_PAD_BOTH меняют сторону дополнения. |
T03-L4 0.35 c | Strings | By default trim() strips only spaces, leaving tabs and newlines intact. | «no» Пояснение: By default, trim() strips whitespace, which includes spaces, tabs, newlines, carriage returns, vertical tabs, and null bytes, not just spaces.
Raw{"answer": "no", "explanation": "By default, trim() strips whitespace, which includes spaces, tabs, newlines, carriage returns, vertical tabs, and null bytes, not just spaces."} | верно | Список символов по умолчанию: « \t\n\r\0\x0B» — пробелы, табы, переводы строк, возврат каретки, null-байт, вертикальный таб. Проверено php -r. |
T03-L5 0.39 c | Strings | How many BYTES does strlen('héllo') return for a UTF-8 string? | «6» Пояснение: In UTF-8, 'h', 'l', 'l', and 'o' are 1 byte each (4 total), while 'é' is 2 bytes, resulting in a total of 6 bytes.
Raw{"answer": 6, "explanation": "In UTF-8, 'h', 'l', 'l', and 'o' are 1 byte each (4 total), while 'é' is 2 bytes, resulting in a total of 6 bytes."} | верно | 6 букв по 2 байта: 12. |
T03-L6 0.34 c | Strings | What does substr('abcdef', -3) return? | «def» Пояснение: substr extracts a portion of the string starting 3 characters from the end, resulting in 'def'.
Raw{"answer": "def", "explanation": "substr extracts a portion of the string starting 3 characters from the end, resulting in 'def'."} | верно | Отрицательное смещение — с конца: def. |
T03-L7 0.35 c | Strings | ucfirst() modifies the string passed to it in place. | «no» Пояснение: ucfirst() does not modify the string in place; it returns a new string with the first character uppercased, while the original string remains unchanged.
Raw```json ⏎ {"answer": "no", "explanation": "ucfirst() does not modify the string in place; it returns a new string with the first character uppercased, while the original string remains unchanged."} ⏎ ``` | верно | Строки неизменяемы; ucfirst возвращает новую строку. |
T03-L8 0.45 c | Strings | Variable interpolation works in heredoc but not in nowdoc. | «yes» Пояснение: Heredoc syntax (<<EOF) allows for variable interpolation and expression evaluation, whereas nowdoc syntax (<<<'EOF') treats the string as a literal value without interpolation.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Heredoc syntax (<<EOF) allows for variable interpolation and expression evaluation, whereas nowdoc syntax (<<<'EOF') treats the string as a literal value without interpolation." ⏎ } | верно | Nowdoc — «одинарные кавычки» в тройном синтаксисе: текст как есть. |
T04-L1 0.31 c | Arrays | The sort() function preserves the key-to-value association of the array. | «no» Пояснение: sort() reindexes numeric keys, whereas asort() preserves key-to-value associations.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "sort() reindexes numeric keys, whereas asort() preserves key-to-value associations." ⏎ } ⏎ ``` | верно | sort перенумеровывает ключи; связь сохраняет asort. |
T04-L2 0.35 c | Arrays | The string key '5' in an array is stored as the integer 5. | «yes» Пояснение: In PHP, string keys in arrays that represent integer values are automatically cast to integers.
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "In PHP, string keys in arrays that represent integer values are automatically cast to integers." ⏎ } ⏎ ``` | верно | Каноничные десятичные строковые ключи приводятся к int. |
T04-L3 0.35 c | Arrays | The in_array() function uses strict comparison (===) by default. | «no» Пояснение: The in_array() function uses loose comparison (==) by default; the $strict parameter must be explicitly set to true to enable strict comparison.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "The in_array() function uses loose comparison (==) by default; the $strict parameter must be explicitly set to true to enable strict comparison." ⏎ } ⏎ ``` | верно | По умолчанию сравнение нестрогое; строгое — третий аргумент true. |
T04-L4 0.43 c | Arrays | Without a callback, array_filter() removes all "empty" (falsy) elements from the array. | «yes» Пояснение: By default, array_filter() removes elements that evaluate to false (0, "0", null, empty array, empty string, false) if no callback is provided.
Raw{"answer": "yes", "explanation": "By default, array_filter() removes elements that evaluate to false (0, \"0\", null, empty array, empty string, false) if no callback is provided."} | верно | Убирает 0, "", null, false и пустые массивы. |
T04-L5 0.33 c | Arrays | By default, array_slice() preserves the original numeric keys of the array. | «yes» Пояснение: By default, the third parameter of array_slice() is false, meaning the original keys are preserved unless explicitly set to true.
Raw{"answer": "yes", "explanation": "By default, the third parameter of array_slice() is false, meaning the original keys are preserved unless explicitly set to true."} | неверно верный: «no» | По умолчанию ключи перенумеровываются; сохранение — preserve_keys = true. |
T04-L6 0.4 c | Arrays | What does array_slice([10, 20, 30, 40], 1, 2) return? | «[20, 30]» Пояснение: array_slice extracts elements starting from index 1 (which is 20) with a length of 2, returning [20, 30].
Raw{"answer": "[20, 30]", "explanation": "array_slice extracts elements starting from index 1 (which is 20) with a length of 2, returning [20, 30]."} | верно | [20,30]; ключи перенумеровываются. |
T04-L7 0.4 c | Arrays | How many elements will count(['a' => 1] + ['a' => 9, 'b' => 2]) return? | «2» Пояснение: The + operator merges arrays, keeping the left side's values for duplicate keys; 'a' remains 1 and 'b' is added, resulting in two elements.
Raw{"answer": 2, "explanation": "The + operator merges arrays, keeping the left side's values for duplicate keys; 'a' remains 1 and 'b' is added, resulting in two elements."} | верно | Оператор + : по ключу 'a' побеждает левый; итого 2. |
T04-L8 0.38 c | Arrays | Since PHP 8.1, the spread operator [...$a, ...$b] supports arrays with string keys. | «no» Пояснение: The spread operator in array literals only supports integer keys; string keys are ignored in PHP versions including 8.1.
Raw{"answer": "no", "explanation": "The spread operator in array literals only supports integer keys; string keys are ignored in PHP versions including 8.1."} | неверно верный: «yes» | В 8.0 — только числовые ключи; 8.1 снял ограничение. |
T05-L1 0.51 c | Functions and closures | Named arguments cannot be combined with argument unpacking ...$args in a single call. | «yes» Пояснение: In PHP 8.0+, named arguments can be used before argument unpacking, but they cannot appear after the unpacking operator (e.g., func(...$args, b: 2) is invalid).
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In PHP 8.0+, named arguments can be used before argument unpacking, but they cannot appear after the unpacking operator (e.g., func(...$args, b: 2) is invalid)." ⏎ } | неверно верный: «no» | Можно: f(...$args, имя: значение). Нельзя только позиционный аргумент после распаковки. |
T05-L2 0.48 c | Functions and closures | An anonymous function without use sees variables from the outer scope. | «no» Пояснение: In PHP, anonymous functions (closures) must explicitly use the 'use' keyword to capture variables from the outer scope by value; without it, they do not have access to those variables.
Raw{"answer": "no", "explanation": "In PHP, anonymous functions (closures) must explicitly use the 'use' keyword to capture variables from the outer scope by value; without it, they do not have access to those variables."} | верно | Без use внешние переменные недоступны; авто-захват только у fn. |
T05-L3 0.09 c | Functions and closures | What will func_num_args() return inside function f($a) { return func_num_args(); } when called as f(1, 2, 3)? | «— (нет ответа)» | не разобрано верный: «3» парсинг: нет | Считает переданные аргументы: 3. |
T05-L4 0.69 c | Functions and closures | The body of an arrow function fn may consist of several expressions in curly braces. | «no» Пояснение: In PHP, an arrow function (fn) with a body containing multiple expressions (i.e., a code block) is defined using regular function syntax (function () { ... }), not the arrow function syntax (fn () => ...). Arrow functions use a single expression without braces.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "In PHP, an arrow function (fn) with a body containing multiple expressions (i.e., a code block) is defined using regular function syntax (function () { ... }), not the arrow function syntax (fn () => ...). Arrow functions use a single expression without braces." ⏎ } ⏎ ``` | верно | fn — всегда одно выражение; блок операторов делает обычная анонимная функция. |
T05-L5 0.41 c | Functions and closures | An arrow function fn captures outer variables by reference (lazily, at use time). | «no» Пояснение: Arrow functions in PHP (introduced in PHP 8) capture outer variables by value at the time of definition, not by reference.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "Arrow functions in PHP (introduced in PHP 8) capture outer variables by value at the time of definition, not by reference." ⏎ } | верно | fn захватывает только по значению, автоматически; по ссылке — только &$var в use у обычной функции (fn так не умеет). |
T05-L6 0.31 c | Functions and closures | A closure declared as static function () {} does not capture $this. | «no» Пояснение: In PHP, static closures do capture $this from the scope in which they are declared.
Raw{"answer": "no", "explanation": "In PHP, static closures do capture $this from the scope in which they are declared."} | неверно верный: «yes» | static-замыкание отвязано от объекта: $this внутри недоступен. |
T05-L7 0.36 c | Functions and closures | What will this print: $x = 5; $f = function () use ($x) { return $x; }; $x = 7; echo $f(); | «5» Пояснение: The closure captures the value of $x (5) at the time of its definition, so changing $x later does not affect the captured value.
Raw{"answer": 5, "explanation": "The closure captures the value of $x (5) at the time of its definition, so changing $x later does not affect the captured value."} | верно | use захватывает по значению в момент создания: 5. |
T05-L8 0.38 c | Functions and closures | In weak typing mode (without strict_types), passing the string "5" to an int parameter is allowed. | «yes» Пояснение: In PHP's weak typing mode, string representations of numbers are automatically coerced to integers when passed to int-typed parameters.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In PHP's weak typing mode, string representations of numbers are automatically coerced to integers when passed to int-typed parameters." ⏎ } | верно | Coercive typing приводит "5" к 5; strict_types=1 требует точного типа. |
T06-L1 0.45 c | OOP: classes and inheritance | PHP supports constructor property promotion: public function __construct(private int $x) {}. | «yes» Пояснение: PHP 8.0 introduced constructor property promotion, allowing parameters in the constructor to be declared with visibility modifiers (public, protected, private) to automatically declare and assign properties.
Raw{"answer": "yes", "explanation": "PHP 8.0 introduced constructor property promotion, allowing parameters in the constructor to be declared with visibility modifiers (public, protected, private) to automatically declare and assign properties."} | верно | С PHP 8.0 параметр с модификатором создаёт свойство и присваивание. |
T06-L2 0.23 c | OOP: classes and inheritance | Which keyword prevents a method from being overridden in subclasses? | «final» Пояснение: The 'final' keyword in PHP prevents a method from being overridden by subclasses.
Raw{"answer": "final", "explanation": "The 'final' keyword in PHP prevents a method from being overridden by subclasses."} | верно | final. |
T06-L3 0.29 c | OOP: classes and inheritance | A method declared final cannot be overridden in a subclass. | «yes» Пояснение: In PHP, a method declared as final cannot be overridden by any method with the same name in a subclass.
Raw{"answer": "yes", "explanation": "In PHP, a method declared as final cannot be overridden by any method with the same name in a subclass."} | верно | final запрещает переопределение метода и наследование класса. |
T06-L4 0.25 c | OOP: classes and inheritance | Parent properties with private visibility are accessible in a subclass. | «no» Пояснение: Private properties in a parent class are not accessible in a subclass.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "Private properties in a parent class are not accessible in a subclass." ⏎ } ⏎ ``` | верно | В подклассе видны protected и public; private — только внутри своего класса. |
T06-L5 0.38 c | OOP: classes and inheritance | What does get_class(new class {}) return? Answer with the part of the name before the NUL byte (without the file path). | «class@anonymous» Пояснение: In PHP, anonymous classes are given a generated name that starts with 'class@anonymous' followed by the file and line number.
Raw{"answer": "class@anonymous", "explanation": "In PHP, anonymous classes are given a generated name that starts with 'class@anonymous' followed by the file and line number."} | верно | get_class анонимного класса печатает class@anonymous\0<файл>:<строка>$n; короткая форма — часть до NUL-байта. Проверено php -r (hex). |
T06-L6 0.55 c | OOP: classes and inheritance | A private parent method is not part of the inheritance contract: a child may declare a method with the same name and any visibility. | «yes» Пояснение: In PHP, a child class can redefine a private parent method with the same name and different visibility without triggering a fatal error, because private methods are not visible to the child and thus do not form part of the inheritance interface.
Raw{"answer": "yes", "explanation": "In PHP, a child class can redefine a private parent method with the same name and different visibility without triggering a fatal error, because private methods are not visible to the child and thus do not form part of the inheritance interface."} | верно | private-члены не наследуются — правила совместимости подписей не действуют. |
T06-L7 0.38 c | OOP: classes and inheritance | The magic method __get() is called only for non-existent properties. | «no» Пояснение: __get() is called when attempting to read an inaccessible property (private/protected) or a non-existent property.
Raw{"answer": "no", "explanation": "__get() is called when attempting to read an inaccessible property (private/protected) or a non-existent property."} | верно | __get срабатывает и для существующих, но недоступных (private/protected извне). |
T06-L8 0.4 c | OOP: classes and inheritance | What does reassigning a readonly property throw — Exception or Error? | «string» Пояснение: In PHP 8.1+, attempting to write to a readonly property throws a ReadonlyPropertyWriteError, which is a subclass of Error.
Raw{"answer": "string", "explanation": "In PHP 8.1+, attempting to write to a readonly property throws a ReadonlyPropertyWriteError, which is a subclass of Error."} | неверно верный: «error» | Error (readonly с 8.1); оговорка: в __clone() переинициализация допустима (8.3+). |
T07-L1 0.27 c | Interfaces, traits, enum | An interface can declare constants. | «yes» Пояснение: In PHP, interfaces can define public constants, though they cannot define methods or properties.
Raw{"answer": "yes", "explanation": "In PHP, interfaces can define public constants, though they cannot define methods or properties."} | верно | Константы интерфейса наследуются реализациями. |
T07-L2 0.27 c | Interfaces, traits, enum | Which operator checks whether an object is an instance of a class or interface? | «instanceof» Пояснение: The 'instanceof' operator in PHP checks if an object is an instance of a specific class or interface.
Raw{"answer": "instanceof", "explanation": "The 'instanceof' operator in PHP checks if an object is an instance of a specific class or interface."} | верно | instanceof. |
T07-L3 0.35 c | Interfaces, traits, enum | An interface can declare static methods. | «yes» Пояснение: In PHP, an interface can declare static methods, but the implementing class must define those static methods with compatible signatures.
Raw```json ⏎ {"answer": "yes", "explanation": "In PHP, an interface can declare static methods, but the implementing class must define those static methods with compatible signatures."} ⏎ ``` | верно | Реализация обязана дать статический метод с той же сигнатурой. |
T07-L4 0.25 c | Interfaces, traits, enum | The instanceof operator only checks class inheritance: it ignores interfaces. | «no» Пояснение: The instanceof operator in PHP checks both class inheritance and interface implementation.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "The instanceof operator in PHP checks both class inheritance and interface implementation." ⏎ } ⏎ ``` | верно | instanceof возвращает true и для интерфейсов объекта. |
T07-L5 0.37 c | Interfaces, traits, enum | An interface method may have a default implementation, like a trait method. | «no» Пояснение: In PHP, interface methods must be abstract (have no body), whereas traits allow for concrete method implementations with default behavior.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "In PHP, interface methods must be abstract (have no body), whereas traits allow for concrete method implementations with default behavior." ⏎ } | верно | Методы интерфейса — только сигнатуры; тело даёт реализующий класс. |
T07-L6 0.35 c | Interfaces, traits, enum | An abstract method in an abstract class may have protected visibility. | «yes» Пояснение: Abstract methods in PHP can have any visibility modifier (public, protected, private) as long as they are declared without a body.
Raw```json ⏎ {"answer": "yes", "explanation": "Abstract methods in PHP can have any visibility modifier (public, protected, private) as long as they are declared without a body."} ⏎ ``` | верно | В абстрактном классе — любая видимость; в интерфейсе — только public. |
T07-L7 0.38 c | Interfaces, traits, enum | How many elements will Foo::cases() return for enum Foo { case A; case B; case C; }? | «3» Пояснение: The `cases()` method in PHP returns an array of all the enum cases, which in this case are A, B, and C, so there are 3 elements.
Raw```json ⏎ {"answer": 3, "explanation": "The `cases()` method in PHP returns an array of all the enum cases, which in this case are A, B, and C, so there are 3 elements."} ⏎ ``` | верно | Статический метод cases(): 3. |
T07-L8 0.35 c | Interfaces, traits, enum | A trait can declare constants. | «yes» Пояснение: In PHP, traits can declare constants just like classes, and these constants are inherited by any class that uses the trait.
Raw{"answer": "yes", "explanation": "In PHP, traits can declare constants just like classes, and these constants are inherited by any class that uses the trait."} | верно | С PHP 8.2 трейты могут объявлять константы (RFC constants_in_traits); до 8.2 — нет. |
T08-L1 0.27 c | Exceptions and errors | The Throwable interface is a common ancestor of both Exception and Error. | «yes» Пояснение: The Throwable interface is the common ancestor for both Exception and Error in PHP.
Raw```json ⏎ {"answer": "yes", "explanation": "The Throwable interface is the common ancestor for both Exception and Error in PHP."} ⏎ ``` | верно | Иерархия с PHP 7: Throwable → Exception и Throwable → Error. |
T08-L2 0.32 c | Exceptions and errors | A catch (Exception $e) block will also catch TypeError, because TypeError ultimately inherits from Exception. | «no» Пояснение: TypeError inherits from Error, not Exception, so it would not be caught by a catch (Exception $e) block.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "TypeError inherits from Error, not Exception, so it would not be caught by a catch (Exception $e) block." ⏎ } ⏎ ``` | верно | TypeError наследуется от Error; catch (Exception) его не ловит. |
T08-L3 0.39 c | Exceptions and errors | The @ operator suppresses exceptions too. | «no» Пояснение: The @ operator suppresses warnings, notices, and errors, but exceptions are thrown and are not suppressed by the @ operator.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "The @ operator suppresses warnings, notices, and errors, but exceptions are thrown and are not suppressed by the @ operator." ⏎ } | верно | @ глушит диагностику (warnings/notices), исключения не перехватывает. |
T08-L4 0.25 c | Exceptions and errors | What error class does intdiv(5, 0) throw? | «divisionbyzeroerror» Пояснение: intdiv() throws a DivisionByZeroError when the divisor is zero.
Raw{"answer": "DivisionByZeroError", "explanation": "intdiv() throws a DivisionByZeroError when the divisor is zero."} | верно | DivisionByZeroError (иерархия Error, не Exception); php-грейдер объективен. |
T08-L5 0.29 c | Exceptions and errors | The finally block runs only if the exception was caught by a catch block. | «no» Пояснение: The finally block executes regardless of whether an exception was caught or not.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "The finally block executes regardless of whether an exception was caught or not." ⏎ } ⏎ ``` | верно | Наоборот: finally выполняется всегда — даже когда исключение не поймано и уходит выше. Проверено php -r. |
T08-L6 0.44 c | Exceptions and errors | An exception thrown inside a finally block has no effect on the result of the try block. | «no» Пояснение: In PHP, if an exception is thrown in a finally block, it is rethrown and overrides any exception that was previously thrown in the try or catch blocks.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "In PHP, if an exception is thrown in a finally block, it is rethrown and overrides any exception that was previously thrown in the try or catch blocks." ⏎ } | верно | Исключение из finally перекрывает исходное и уходит вместо него. |
T08-L7 0.25 c | Exceptions and errors | What does the expression (bool) new Exception('x') return? | «yes» Пояснение: Casting an object to a boolean in PHP always results in true.
Raw{"answer": "yes", "explanation": "Casting an object to a boolean in PHP always results in true."} | верно | Любой объект при приведении к bool — true. Формы ответа: true или да. |
T08-L8 0.37 c | Exceptions and errors | Functions registered via register_shutdown_function() run when exit is called. | «yes» Пояснение: Shutdown functions registered with register_shutdown_function() are executed when the script shuts down, which includes cases where exit() or die() is called.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Shutdown functions registered with register_shutdown_function() are executed when the script shuts down, which includes cases where exit() or die() is called." ⏎ } | верно | exit завершает скрипт, но shutdown-функции отрабатывают. |
T09-L1 0.48 c | Namespaces and autoloading | The use App\Service\Mailer; statement itself loads the class file. | «no» Пояснение: The use statement in PHP is a compile-time construct that creates an alias for a fully qualified class name; it does not trigger the autoloading or inclusion of the class file.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "The use statement in PHP is a compile-time construct that creates an alias for a fully qualified class name; it does not trigger the autoloading or inclusion of the class file." ⏎ } ⏎ ``` | верно | use — псевдоним на этапе компиляции; файл грузит автозагрузчик при первом обращении. |
T09-L2 0.36 c | Namespaces and autoloading | What follows use to import a function (not a class): the word function or const? | «function» Пояснение: In PHP 8.0+, the 'function' keyword is used to import individual functions, while 'const' is used for constants.
Raw{"answer": "function", "explanation": "In PHP 8.0+, the 'function' keyword is used to import individual functions, while 'const' is used for constants."} | верно | use function ...; (и use const для констант). |
T09-L3 0.38 c | Namespaces and autoloading | Into which file (path from src/) does the PSR-4 mapping "App\ → src/" place the class App\Controller\Api\UserController? | «src/controller/api/usercontroller.php» Пояснение: PSR-4 converts namespace backslashes to directory slashes and appends the filename with a .php extension.
Raw{"answer": "src/Controller/Api/UserController.php", "explanation": "PSR-4 converts namespace backslashes to directory slashes and appends the filename with a .php extension."} | верно | Остаток имени после префикса, \ → /. |
T09-L4 0.44 c | Namespaces and autoloading | Including vendor/autoload.php registers autoloaders via spl_autoload_register(). | «yes» Пояснение: Composer's autoloader generated in vendor/autoload.php uses spl_autoload_register to add its loading rules to PHP's spl_autoload functions.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Composer's autoloader generated in vendor/autoload.php uses spl_autoload_register to add its loading rules to PHP's spl_autoload functions." ⏎ } | верно | Composer ставит автозагрузчик именно на spl_autoload_register. |
T09-L5 0.29 c | Namespaces and autoloading | The magic constant __NAMESPACE__ contains the name of the current namespace. | «yes» Пояснение: The magic constant __NAMESPACE__ indeed returns the fully qualified name of the current namespace, or an empty string if the file is in the global namespace.
Raw{"answer": "yes", "explanation": "The magic constant __NAMESPACE__ indeed returns the fully qualified name of the current namespace, or an empty string if the file is in the global namespace."} | верно | В корневом пространстве — пустая строка. |
T09-L6 0.28 c | Namespaces and autoloading | An unqualified class name (without a leading \) in new is resolved from the global root. | «no» Пояснение: An unqualified class name in the `new` expression is resolved relative to the current namespace, not the global root.
Raw{"answer": "no", "explanation": "An unqualified class name in the `new` expression is resolved relative to the current namespace, not the global root."} | верно | Резолвится относительно текущего namespace (с учётом импортов). |
T09-L7 0.44 c | Namespaces and autoloading | With the PSR-4 mapping "App\ → src/", the class App\Model\User lives in the file src/Model/User.php. | «yes» Пояснение: PSR-4 requires that the relative namespace name after the prefix (Model\User) be converted to a file path (Model/User.php) relative to the base directory (src/).
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "PSR-4 requires that the relative namespace name after the prefix (Model\\User) be converted to a file path (Model/User.php) relative to the base directory (src/)." ⏎ } | верно | Остаток имени после префикса переносится в путь как есть. |
T09-L8 0.33 c | Namespaces and autoloading | A use statement may be written inside a function body — the import then applies to that function only. | «yes» Пояснение: PHP allows use statements inside functions, and the import applies only to the function's local scope.
Raw{"answer": "yes", "explanation": "PHP allows use statements inside functions, and the import applies only to the function's local scope."} | неверно верный: «no» | use внутри тела функции — parse error; импорты файловые и компиляционные. |
T10-L1 0.43 c | References and scope | Arrays are copied on assignment rather than passed by reference. | «yes» Пояснение: By default, PHP arrays are value types and are copied when assigned to another variable, meaning modifications to one do not affect the other unless reference syntax is used.
Raw{"answer": "yes", "explanation": "By default, PHP arrays are value types and are copied when assigned to another variable, meaning modifications to one do not affect the other unless reference syntax is used."} | верно | Присваивание массива — копия (в движке — copy-on-write). |
T10-L2 0.3 c | References and scope | What will this print: $a = [1, 2]; $b = $a; $b[] = 3; echo count($a); | «2» Пояснение: In PHP, arrays are value types, so $b is a copy of $a; modifying $b does not affect $a.
Raw{"answer": 2, "explanation": "In PHP, arrays are value types, so $b is a copy of $a; modifying $b does not affect $a."} | верно | Присваивание — копия: в $a по-прежнему 2 элемента. |
T10-L3 0.49 c | References and scope | Inside a function, user-defined global variables are inaccessible without global, $GLOBALS, or passing them as parameters. | «yes» Пояснение: In PHP, user-defined global variables are not automatically accessible within function scope; they must be accessed via the `global` keyword, the `$GLOBALS` superglobal array, or passed as parameters.
Raw```json ⏎ {"answer": "yes", "explanation": "In PHP, user-defined global variables are not automatically accessible within function scope; they must be accessed via the `global` keyword, the `$GLOBALS` superglobal array, or passed as parameters."} ⏎ ``` | верно | Область видимости функций изолирована; исключение — суперглобалы ($_GET и др.). |
T10-L4 0.37 c | References and scope | unset($GLOBALS['x']) inside a function removes the global variable only for that function. | «no» Пояснение: The $GLOBALS array is a reference to the global symbol table, so unset($GLOBALS['x']) removes the variable from the global scope, not just locally.
Raw{"answer": "no", "explanation": "The $GLOBALS array is a reference to the global symbol table, so unset($GLOBALS['x']) removes the variable from the global scope, not just locally."} | верно | $GLOBALS — прямое окно в глобальную область: unset удалит её по-настоящему. |
T10-L5 0.32 c | References and scope | What will this print: function inc(&$x) { $x++; } $n = 5; inc($n); echo $n; | «6» Пояснение: The parameter $x is passed by reference, so incrementing $x inside the function directly modifies $n.
Raw{"answer": 6, "explanation": "The parameter $x is passed by reference, so incrementing $x inside the function directly modifies $n."} | верно | Ссылка меняет оригинал: 6. |
T10-L6 0.45 c | References and scope | A foreach over an array (by value) works with the "live" array: changes to the array inside the loop are visible in the same pass. | «no» Пояснение: PHP copies the array for by-value foreach, so external mutations during the loop are not visible.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "PHP copies the array for by-value foreach, so external mutations during the loop are not visible." ⏎ } ⏎ ``` | верно | По значению foreach итерирует копию-снимок. |
T10-L7 0.25 c | References and scope | A static property belongs to each instance separately: changes in one object are not visible in others. | «no» Пояснение: Static properties are shared among all instances of a class, so changes in one object are visible in others.
Raw{"answer": "no", "explanation": "Static properties are shared among all instances of a class, so changes in one object are visible in others."} | верно | Наоборот: статическое свойство общее для всех экземпляров класса. Проверено php -r. |
T10-L8 0.35 c | References and scope | An array can have a boolean key true, and it will be stored as bool. | «no» Пояснение: In PHP, array keys of type boolean are cast to integers (true becomes 1, false becomes 0) rather than remaining as boolean keys.
Raw{"answer": "no", "explanation": "In PHP, array keys of type boolean are cast to integers (true becomes 1, false becomes 0) rather than remaining as boolean keys."} | верно | Булев ключ приводится к int: true → 1, false → 0. |
T11-L1 0.44 c | Generators, iterators, SPL | Inside a generator, return with a value can be used, and it becomes available via $gen->getReturn(). | «yes» Пояснение: In PHP generators, the value passed to the 'return' statement can be accessed using the 'getReturn()' method on the Generator object.
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "In PHP generators, the value passed to the 'return' statement can be accessed using the 'getReturn()' method on the Generator object." ⏎ } ⏎ ``` | верно | return-значение генератора доступно через getReturn() после прохода. |
T11-L2 0.61 c | Generators, iterators, SPL | A fully consumed generator can be rewound with rewind() and traversed again. | «no» Пояснение: A generator in PHP is a one-time iterator; once it is fully consumed (reaches the end of its loop), it cannot be rewound and traversed again using rewind(). You would need to recreate the generator.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "A generator in PHP is a one-time iterator; once it is fully consumed (reaches the end of its loop), it cannot be rewound and traversed again using rewind(). You would need to recreate the generator." ⏎ } ⏎ ``` | верно | Генератор одноразовый: rewind после начала итерации бросает Exception. |
T11-L3 3.5 c | Generators, iterators, SPL | The yield from construct delegates traversal to another generator or iterable. | «yes» Пояснение: The yield from syntax in Python (not native PHP, but commonly discussed in generator contexts) delegates iteration to another iterable; however, in pure PHP, this is manually implemented, but the statement describes the concept correctly for languages like Python where it is a keyword. Note: Strictly speaking, PHP does not have a 'yield from' keyword, but if the question implies the concept or a polyfill/library context, it is functionally true. Given the phrasing, it likely refers to the general programming concept or a specific library implementation, but in standard PHP core, there is no `yield from` keyword. Wait, let's re-read. "The yield from construct...". PHP does NOT have a `yield from` keyword in its language specification. It has `yield`. If this is a strict PHP question, the answer should be False because the syntax `yield from` does not exist in PHP 8.2/8.3. It exists in Python, Ruby, etc. In PHP, you use `yield from` only if using a library or if the question is misidentifying the language. However, many PHP developers know it from Python. Let's look at the options. If it's a trick question about PHP specifics, it's False. If it's a general concept question mislabeled as PHP, it's True. But the prompt says "You are taking a PHP knowledge test". In PHP, there is no `yield from` keyword. You manually loop and yield. Therefore, the statement is technically false for native PHP syntax. However, some might argue it's a conceptual description. Let's check if there's a recent proposal or polyfill. No, it's not in the language. So, "False" is the most accurate technical answer for a *PHP* test unless it refers to a specific library. But usually, these tests are about language features. Python has `yield from`. PHP does not. Answer: No.
Raw{"answer": "yes", "explanation": "The yield from syntax in Python (not native PHP, but commonly discussed in generator contexts) delegates iteration to another iterable; however, in pure PHP, this is manually implemented, but the statement describes the concept correctly for languages like Python where it is a keyword. Note: Strictly speaking, PHP does not have a 'yield from' keyword, but if the question implies the concept or a polyfill/library context, it is functionally true. Given the phrasing, it likely refers to the general programming concept or a specific library implementation, but in standard PHP core, there is no `yield from` keyword. Wait, let's re-read. \"The yield from construct...\". PHP does NOT have a `yield from` keyword in its language specification. It has `yield`. If this is a strict PHP question, the answer should be False because the syntax `yield from` does not exist in PHP 8.2/8.3. It exists in Python, Ruby, etc. In PHP, you use `yield from` only if using a library or if the question is misidentifying the language. However, many PHP developers know it from Python. Let's look at the options. If it's a trick question about PHP specifics, it's False. If it's a general concept question mislabeled as PHP, it's True. But the prompt says \"You are taking a PHP knowledge test\". In PHP, there is no `yield from` keyword. You manually loop and yield. Therefore, the statement is technically false for native PHP syntax. However, some might argue it's a conceptual description. Let's check if there's a recent proposal or polyfill. No, it's not in the language. So, \"False\" is the most accurate technical answer for a *PHP* test unless it refers to a specific library. But usually, these tests are about language features. Python has `yield from`. PHP does not. Answer: No."} | верно | yield from проксирует значения, ключи и return-значение внутреннего генератора. |
T11-L4 0.31 c | Generators, iterators, SPL | What does get_class(g()) return for function g() { yield 1; }? | «generator» Пояснение: A function containing a yield statement returns a Generator object when called.
Raw{"answer": "Generator", "explanation": "A function containing a yield statement returns a Generator object when called."} | верно | Функция с yield возвращает Generator. |
T11-L5 0.3 c | Generators, iterators, SPL | How many elements will count(iterator_to_array((function () { yield from [1, 2, 3]; })())) return? | «3» Пояснение: iterator_to_array converts the generator yielding 3 values into an array with 3 elements, which count() then returns.
Raw{"answer": 3, "explanation": "iterator_to_array converts the generator yielding 3 values into an array with 3 elements, which count() then returns."} | верно | yield from делегирует все 3 элемента. |
T11-L6 0.28 c | Generators, iterators, SPL | The SplStack class implements a FIFO queue. | «no» Пояснение: SplStack implements a LIFO (Last In, First Out) stack, not a FIFO queue.
Raw```json ⏎ {"answer": "no", "explanation": "SplStack implements a LIFO (Last In, First Out) stack, not a FIFO queue."} ⏎ ``` | верно | SplStack — стек LIFO; очередь FIFO — SplQueue. |
T11-L7 0.35 c | Generators, iterators, SPL | ArrayIterator allows wrapping an array and traversing it via the Iterator interface. | «yes» Пояснение: ArrayIterator is a SPL class that wraps an array and implements the Iterator interface, enabling it to be traversed in foreach loops or other iterator contexts.
Raw{"answer": "yes", "explanation": "ArrayIterator is a SPL class that wraps an array and implements the Iterator interface, enabling it to be traversed in foreach loops or other iterator contexts."} | верно | Объектная обёртка над массивом. |
T11-L8 0.25 c | Generators, iterators, SPL | An ArrayObject instance cannot be traversed with foreach. | «no» Пояснение: ArrayObject implements the Traversable interface, so it can be traversed with foreach.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "ArrayObject implements the Traversable interface, so it can be traversed with foreach." ⏎ } | верно | ArrayObject реализует IteratorAggregate — foreach по нему работает. |
T12-L1 0.39 c | Configuration and security | password_hash() generates a salt automatically — passing one separately is not needed. | «yes» Пояснение: In PHP, the password_hash() function automatically generates and includes a random salt, so there is no need to provide a salt separately.
Raw```json ⏎ {"answer": "yes", "explanation": "In PHP, the password_hash() function automatically generates and includes a random salt, so there is no need to provide a salt separately."} ⏎ ``` | верно | Соль встраивается в строку результата; параметр salt устарел. |
T12-L2 0.27 c | Configuration and security | In PHP 8, PASSWORD_DEFAULT is md5 with an automatically added salt. | «no» Пояснение: PASSWORD_DEFAULT in PHP 8 is argon2id, not md5.
Raw```json ⏎ {"answer": "no", "explanation": "PASSWORD_DEFAULT in PHP 8 is argon2id, not md5."} ⏎ ``` | верно | PASSWORD_DEFAULT — bcrypt; md5 для паролей непригоден (перебирается массово). |
T12-L3 0.35 c | Configuration and security | What does password_verify('secret', password_hash('secret', PASSWORD_DEFAULT)) return? | «yes» Пояснение: password_verify returns true if the password matches the hash, and in PHP, true is equivalent to yes for this context.
Raw{"answer": "yes", "explanation": "password_verify returns true if the password matches the hash, and in PHP, true is equivalent to yes for this context."} | верно | Соль и хеш в одной строке: true (форма ответа: true или да). |
T12-L4 0.45 c | Configuration and security | strip_tags() protects against SQL injection. | «no» Пояснение: strip_tags() is designed to remove HTML and PHP tags from a string, primarily to prevent Cross-Site Scripting (XSS) issues, whereas SQL injection is best prevented by using prepared statements and parameterized queries.
Raw{"answer": "no", "explanation": "strip_tags() is designed to remove HTML and PHP tags from a string, primarily to prevent Cross-Site Scripting (XSS) issues, whereas SQL injection is best prevented by using prepared statements and parameterized queries."} | верно | strip_tags режет HTML-теги (помощник против XSS), к параметризации SQL отношения не имеет. |
T12-L5 0.39 c | Configuration and security | session_regenerate_id() is used to protect against session fixation upon user login. | «yes» Пояснение: session_regenerate_id() creates a new session ID, which is a standard security practice to prevent session fixation attacks by invalidating any previously known IDs.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "session_regenerate_id() creates a new session ID, which is a standard security practice to prevent session fixation attacks by invalidating any previously known IDs." ⏎ } | верно | Новый ID сессии после логина — стандартная защита от session fixation. |
T12-L6 0.25 c | Configuration and security | Which built-in function returns the SAPI name (e.g., cli)? | «php_sapi_name» Пояснение: The php_sapi_name function returns the current SAPI name as a string.
Raw{"answer": "php_sapi_name", "explanation": "The php_sapi_name function returns the current SAPI name as a string."} | верно | php_sapi_name(). |
T12-L7 0.31 c | Configuration and security | session_destroy() deletes session data on the server but not the cookie in the user's browser. | «yes» Пояснение: session_destroy() removes the session data stored on the server but does not automatically remove the PHPSESSID cookie from the client's browser.
Raw{"answer": "yes", "explanation": "session_destroy() removes the session data stored on the server but does not automatically remove the PHPSESSID cookie from the client's browser."} | верно | Удаление cookie — отдельный шаг через setcookie с истёкшим сроком. |
T12-L8 0.33 c | Configuration and security | Without calling session_start(), the $_SESSION array is automatically populated with session data. | «no» Пояснение: The $_SESSION superglobal is only populated with session data after the session_start() function has been called and the session has been initiated.
Raw{"answer": "no", "explanation": "The $_SESSION superglobal is only populated with session data after the session_start() function has been called and the session has been initiated."} | верно | Без session_start() данные сессии в массив не загружаются ($_SESSION можно заполнить вручную, но привязки к сессии нет). |
VC-L1 0.25 c | PHP 8.4–8.5 | In which PHP version was the array_find() function introduced? | «8.3.0» Пояснение: The array_find() function was introduced in PHP 8.3.0.
Raw{"answer": "8.3.0", "explanation": "The array_find() function was introduced in PHP 8.3.0."} | неверно верный: «8.4» | PHP 8.4 (RFC array_find). |
VC-L2 0.29 c | PHP 8.4–8.5 | Property hooks (get/set right in the property declaration) landed in PHP 8.4. | «yes» Пояснение: PHP 8.4 introduced property hooks, allowing getter and setter logic to be defined directly within the property declaration.
Raw{"answer": "yes", "explanation": "PHP 8.4 introduced property hooks, allowing getter and setter logic to be defined directly within the property declaration."} | верно | Property hooks — PHP 8.4 (ноябрь 2024). |
VC-L3 0.25 c | PHP 8.4–8.5 | Asymmetric visibility (public private(set) string $name) appeared in PHP 8.4. | «yes» Пояснение: Asymmetric visibility, such as public private(set) properties, was introduced in PHP 8.4.
Raw{"answer": "yes", "explanation": "Asymmetric visibility, such as public private(set) properties, was introduced in PHP 8.4."} | верно | Asymmetric visibility v2 — PHP 8.4. |
VC-L4 0.33 c | PHP 8.4–8.5 | In which PHP version was the #[\NoDiscard] attribute introduced? Answer with the version number. | «8.4» Пояснение: The #[\NoDiscard] attribute was introduced in PHP 8.4 to allow marking expressions that should not be discarded.
Raw{"answer": 8.4, "explanation": "The #[\\NoDiscard] attribute was introduced in PHP 8.4 to allow marking expressions that should not be discarded."} | неверно верный: «8.5» | #[\NoDiscard] — PHP 8.5 (marking return values as important). |
VC-L5 0.27 c | PHP 8.4–8.5 | In which PHP version did the pipe operator |> first appear? Answer with the version number. | «8.4» Пояснение: The pipe operator |> was introduced in PHP 8.4 as a new feature.
Raw{"answer": "8.4", "explanation": "The pipe operator |> was introduced in PHP 8.4 as a new feature."} | неверно верный: «8.5» | Pipe operator — PHP 8.5 (2025). |
VC-L6 0.36 c | PHP 8.4–8.5 | In which PHP version did clone-with — the syntax clone($obj, ['x' => 1]) — appear? Answer with the version number. | «8.4» Пояснение: The clone-with syntax, which allows cloning an object with specific property values, was introduced in PHP 8.4.
Raw{"answer": "8.4", "explanation": "The clone-with syntax, which allows cloning an object with specific property values, was introduced in PHP 8.4."} | неверно верный: «8.5» | Clone with v2 — PHP 8.5. |
VC-L7 0.23 c | PHP 8.4–8.5 | In which PHP version were the array_first() and array_last() functions introduced? | «8.4» Пояснение: The array_first() and array_last() functions were introduced in PHP 8.4.
Raw{"answer": "8.4", "explanation": "The array_first() and array_last() functions were introduced in PHP 8.4."} | неверно верный: «8.5» | PHP 8.5. |
VC-L8 0.24 c | PHP 8.4–8.5 | For which PHP version was RFC Partial Function Application v2 adopted (as of 2026-11-07)? Answer with the version number. | «8.4» Пояснение: RFC Partial Function Application v2 was adopted for PHP 8.4.
Raw{"answer": 8.4, "explanation": "RFC Partial Function Application v2 was adopted for PHP 8.4."} | неверно верный: «8.6» | PFA v2 принят 05.12.2025 (33-0-0), реализован в PHP 8.6. |
VF-L1 0.38 c | PHP: 8.6+ and the future | For which PHP version was the RFC clamp_v2 (the clamp() function) implemented, as of 2026-11-07? Answer with the version number. | «8.4» Пояснение: The clamp() function was introduced in PHP 8.4 via the RFC "Clamp function" (clamp_v2).
Raw{"answer": "8.4", "explanation": "The clamp() function was introduced in PHP 8.4 via the RFC \"Clamp function\" (clamp_v2)."} | неверно верный: «8.6» | По данным владельца (wiki.php.net/rfc): clamp_v2 — 8.6; clamp() в 8.5.11 отсутствует (косвенное подтверждение). Дата-якорь делает клетку монотонной. |
VF-L2 1.21 c | PHP: 8.6+ and the future | RFC Context Managers v2 has already been adopted in PHP (as of 2026-11-07). | «no» Пояснение: PHP RFC Context Managers (or similar proposals) are generally in the proposal/discussion stage as of late 2024, and have not been formally adopted into the language spec as a released feature by November 2026 in current known roadmaps (it is a future projection, but the statement claims it 'has already been adopted' as a fact for that specific date which is likely false based on typical PHP development cycles where context managers are still being debated).
Raw{"answer": "no", "explanation": "PHP RFC Context Managers (or similar proposals) are generally in the proposal/discussion stage as of late 2024, and have not been formally adopted into the language spec as a released feature by November 2026 in current known roadmaps (it is a future projection, but the statement claims it 'has already been adopted' as a fact for that specific date which is likely false based on typical PHP development cycles where context managers are still being debated)."} | верно | На 06.11.2026 — в обсуждении (создан 2026-10-23); не принят. |
VF-L3 0.52 c | PHP: 8.6+ and the future | RFC Bound-Erased Generic Types (generics) was declined in 2026. | «no» Пояснение: RFC 5174 for generics was actually merged and released in PHP 8.4 in November 2024, not declined in 2026.
Raw{"answer": "no", "explanation": "RFC 5174 for generics was actually merged and released in PHP 8.4 in November 2024, not declined in 2026."} | неверно верный: «yes» | Голосование завершилось 2026-06-28: отклонён (wiki.php.net/rfc). |
VF-L4 0.67 c | PHP: 8.6+ and the future | As of 2026-11-07, the RFC enabling multithreading (ZTS) by default has already been accepted in PHP. | «no» Пояснение: As of late 2025/early 2026, PHP still defaults to the NTS (Non-Thread-Safe) build, and the RFC to make ZTS the default has not been officially accepted for the next major release cycle (e.g., PHP 8.4 or 9.0) as of the specified date.
Raw{"answer": "no", "explanation": "As of late 2025/early 2026, PHP still defaults to the NTS (Non-Thread-Safe) build, and the RFC to make ZTS the default has not been officially accepted for the next major release cycle (e.g., PHP 8.4 or 9.0) as of the specified date."} | верно | Такого принятого RFC нет на дату якоря; якорь делает клетку монотонной — при принятии RFC позже клетка не перевернётся. |
VF-L5 0.62 c | PHP: 8.6+ and the future | As of PHP 8.5, generics (parameterized types) are still absent. | «yes» Пояснение: PHP does not have built-in generic types (parameterized types) as of PHP 8.4, and while generics were proposed for PHP 8.5, they have not been implemented in the stable release, meaning they are still absent.
Raw{"answer": "yes", "explanation": "PHP does not have built-in generic types (parameterized types) as of PHP 8.4, and while generics were proposed for PHP 8.5, they have not been implemented in the stable release, meaning they are still absent."} | верно | Generics в PHP отсутствуют; отрицательный контроль (не путать с C#/Java). |
VF-L6 1.98 c | PHP: 8.6+ and the future | As of 2026-11-07, the latest stable PHP version is 8.5, and PHP 8.6 has not been released yet (GA — 2026-11-19). | «no» Пояснение: PHP follows a release cycle of one feature release per year, so PHP 8.5 should have been released in November 2025 and PHP 8.6 is the next major version scheduled for November 2026; therefore, as of Nov 7, 2026 (which is before the Nov 19, 2026 GA), PHP 8.6 is the version being prepared/released, but the statement is tricky. Let's re-evaluate standard PHP release dates. PHP 8.4 was released Nov 21, 2024. PHP 8.5 is scheduled for Nov 20, 2025. PHP 8.6 is scheduled for Nov 19, 2026. If the date is Nov 7, 2026, PHP 8.5 is the current stable version (released ~Nov 20, 2025). PHP 8.6 GA is Nov 19, 2026, which is in the future relative to Nov 7, 2026. Thus, the statement that 8.5 is the latest stable and 8.6 has not yet been released is True.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "PHP follows a release cycle of one feature release per year, so PHP 8.5 should have been released in November 2025 and PHP 8.6 is the next major version scheduled for November 2026; therefore, as of Nov 7, 2026 (which is before the Nov 19, 2026 GA), PHP 8.6 is the version being prepared/released, but the statement is tricky. Let's re-evaluate standard PHP release dates. PHP 8.4 was released Nov 21, 2024. PHP 8.5 is scheduled for Nov 20, 2025. PHP 8.6 is scheduled for Nov 19, 2026. If the date is Nov 7, 2026, PHP 8.5 is the current stable version (released ~Nov 20, 2025). PHP 8.6 GA is Nov 19, 2026, which is in the future relative to Nov 7, 2026. Thus, the statement that 8.5 is the latest stable and 8.6 has not yet been released is True." ⏎ } | неверно верный: «yes» | 8.5 — релиз осени 2025; 8.6 GA 19.11.2026 (wiki.php.net/todo/php86). Дата снимка — 06.11.2026. |
VF-L7 0.46 c | PHP: 8.6+ and the future | The PHP 6 branch never shipped: after PHP 5.6 came PHP 7.0 directly. | «yes» Пояснение: PHP 6 was a development branch (based on PHP 5.4) that was discontinued and replaced by PHP 7.0, which was released after PHP 5.6.
Raw{"answer": "yes", "explanation": "PHP 6 was a development branch (based on PHP 5.4) that was discontinued and replaced by PHP 7.0, which was released after PHP 5.6."} | верно | Исторический факт: ветка 6 не была релизнута. |
VF-L8 0.35 c | PHP: 8.6+ and the future | The RFC adding the #[\Deprecated] attribute to the core was adopted. | «yes» Пояснение: RFC 0801, which adds the #\Deprecated attribute, was adopted for PHP 8.4.
Raw{"answer": "yes", "explanation": "RFC 0801, which adds the #\\Deprecated attribute, was adopted for PHP 8.4."} | верно | #[\Deprecated] — принят, реализован в PHP 8.4. |
T25-L1 0.5 c | Clean architecture | The dependency rule of clean and onion architecture: inner layers know nothing about outer ones — dependencies point toward the center. | «yes» Пояснение: In Clean and Onion architectures, the Dependency Rule dictates that source code dependencies must point only inward, toward the core business logic, ensuring inner layers remain independent of outer details like frameworks or databases.
Raw{"answer": "yes", "explanation": "In Clean and Onion architectures, the Dependency Rule dictates that source code dependencies must point only inward, toward the core business logic, ensuring inner layers remain independent of outer details like frameworks or databases."} | верно | Чистая (Robert C. Martin), луковичная (Jeffrey Palermo) и гексагональная (ports & adapters) — варианты одной идеи: зависимости направлены внутрь, к домену. Слоями в проекте следит deptrac. |
T25-L2 0.43 c | Clean architecture | Domain entities import neither Doctrine nor Symfony — only the language and, possibly, the standard library. | «yes» Пояснение: Domain entities should be framework-agnostic and typically extend only base PHP classes or use standard libraries, without directly importing Doctrine or Symfony dependencies.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Domain entities should be framework-agnostic and typically extend only base PHP classes or use standard libraries, without directly importing Doctrine or Symfony dependencies." ⏎ } | верно | Изоляция домена от инфраструктуры; deptrac в проекте как раз следит за слоями. |
T25-L3 0.25 c | Clean architecture | Controllers and Twig templates belong to the business-logic layer because they are the ones calling use cases. | «no» Пояснение: Controllers and views belong to the presentation layer, not the business-logic layer.
Raw{"answer": "no", "explanation": "Controllers and views belong to the presentation layer, not the business-logic layer."} | верно | Наоборот: это интерфейсные адаптеры (внешний слой); они зависят от use cases, а не наоборот. |
T25-L4 0.33 c | Clean architecture | What sits at the very center of the onion architecture? | «entities» Пояснение: In Onion Architecture, the innermost layer consists of the core business entities and domain logic that are independent of any external framework or technology.
Raw{"answer": "Entities", "explanation": "In Onion Architecture, the innermost layer consists of the core business entities and domain logic that are independent of any external framework or technology."} | неверно верный: «domain model» | Центральное кольцо — Domain Model: сущности и бизнес-правила без зависимостей; далее Domain Services → Application Services → Infrastructure/UI/Tests (Palermo). |
T25-L5 0.31 c | Clean architecture | Layer boundary violations can be caught automatically: a layer-dependency analyzer (e.g. deptrac) fails on a forbidden call. | «yes» Пояснение: Tools like deptrac analyze static dependencies and can enforce layer boundaries by failing the build when forbidden calls are detected.
Raw{"answer": "yes", "explanation": "Tools like deptrac analyze static dependencies and can enforce layer boundaries by failing the build when forbidden calls are detected."} | верно | depfile.yaml в проекте TasK: CI проверяет правила слоёв на каждом пайплайне. |
T25-L6 0.46 c | Clean architecture | A use case (interactor) may accept an HTTP request or an EntityManager as arguments — it is simpler that way. | «no» Пояснение: A use case (interactor) should not accept framework-specific types like HTTP requests or EntityManagers, as this violates decoupling and makes the use case harder to test and reuse.
Raw```json ⏎ {"answer": "no", "explanation": "A use case (interactor) should not accept framework-specific types like HTTP requests or EntityManagers, as this violates decoupling and makes the use case harder to test and reuse."} ⏎ ``` | верно | Use case принимает DTO и порты; привязка к HTTP/ORM протекает инфраструктуру во внутренние слои. |
T25-L7 0.38 c | Clean architecture | What is the component called that provides a collection of aggregates/entities while hiding the storage mechanism behind an interface? | «repository» Пояснение: In Domain-Driven Design, a Repository abstracts the storage mechanism and provides a collection-like interface for managing entities.
Raw{ ⏎ "answer": "Repository", ⏎ "explanation": "In Domain-Driven Design, a Repository abstracts the storage mechanism and provides a collection-like interface for managing entities."} | верно | Repository pattern (DDD/Evans); в проекте — Doctrine-репозитории за портами. |
T25-L8 0.57 c | Clean architecture | In clean architecture, swapping PostgreSQL for another database touches only the outer layer — the domain and use cases stay unchanged. | «yes» Пояснение: In clean architecture, the domain and use cases depend on abstractions (interfaces), so changing the database (e.g., from PostgreSQL to another) only affects the adapters/frameworks layer, leaving the core domain and use cases unchanged.
Raw```json ⏎ {"answer": "yes", "explanation": "In clean architecture, the domain and use cases depend on abstractions (interfaces), so changing the database (e.g., from PostgreSQL to another) only affects the adapters/frameworks layer, leaving the core domain and use cases unchanged."} ⏎ ``` | верно | Следствие правила зависимостей: инфраструктура взаимозаменяема. |
T26-L1 0.43 c | DDD | In DDD, an aggregate is just another name for a database table. | «no» Пояснение: An aggregate in Domain-Driven Design is a cluster of related entities and value objects that are treated as a single unit for consistency purposes, not simply a database table.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "An aggregate in Domain-Driven Design is a cluster of related entities and value objects that are treated as a single unit for consistency purposes, not simply a database table." ⏎ } ⏎ ``` | верно | Агрегат — кластер объектов с границей согласованности (транзакционной вокруг корня); таблица — деталь хранения. |
T26-L2 0.43 c | DDD | A Value Object is immutable and compared by the values of its fields, not by identity. | «yes» Пояснение: Value Objects are defined by their data rather than their identity, and changing their state typically involves creating a new instance to maintain immutability.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Value Objects are defined by their data rather than their identity, and changing their state typically involves creating a new instance to maintain immutability." ⏎ } | верно | Классика Evans: Money, Email; равенство структурное. |
T26-L3 0.29 c | DDD | What is the single external entry point of an aggregate, through which all changes must go, called? | «root» Пояснение: In Domain-Driven Design, the aggregate root is the single external entry point and guarantees consistency within the aggregate.
Raw{"answer": "Root", "explanation": "In Domain-Driven Design, the aggregate root is the single external entry point and guarantees consistency within the aggregate."} | неверно верный: «aggregate root» | Aggregate Root: внешние объекты ссылаются только на корень; он защищает инварианты агрегата. |
T26-L4 0.33 c | DDD | In DDD, a repository is declared for an aggregate (its root), not for every entity. | «yes» Пояснение: In Domain-Driven Design, repositories are defined for aggregate roots to ensure that the entire aggregate is treated as a single unit of consistency and transactional integrity.
Raw{"answer": "yes", "explanation": "In Domain-Driven Design, repositories are defined for aggregate roots to ensure that the entire aggregate is treated as a single unit of consistency and transactional integrity."} | верно | Репозиторий корня хранит границу согласованности агрегата; вложенные сущности доступны только через корень. |
T26-L5 0.39 c | DDD | Ubiquitous language is the model's shared language common to developers and domain experts. | «yes» Пояснение: Ubiquitous Language is a core concept in Domain-Driven Design (DDD) where the terminology used in the codebase matches the business language used by domain experts and developers to minimize miscommunication.
Raw{"answer": "yes", "explanation": "Ubiquitous Language is a core concept in Domain-Driven Design (DDD) where the terminology used in the codebase matches the business language used by domain experts and developers to minimize miscommunication."} | верно | Evans: язык из требований переходит в имена классов и методов. |
T26-L6 0.56 c | DDD | What is the boundary called within which a model and its language are consistent, while outside the same words mean other models? | «universe» Пояснение: In the context of set theory and model theory, the 'universe' or 'domain' defines the collection of objects within which the axioms and language of a model are consistent and interpreted; outside this set, symbols may refer to different objects in other models.
Raw{"answer": "universe", "explanation": "In the context of set theory and model theory, the 'universe' or 'domain' defines the collection of objects within which the axioms and language of a model are consistent and interpreted; outside this set, symbols may refer to different objects in other models."} | неверно верный: «bounded context» | Bounded Context; «Заказ» в биллинге и в доставке — разные модели. |
T26-L7 0.37 c | DDD | An anemic model (objects with only getters/setters, logic in services) is the recommended DDD style. | «no» Пояснение: DDD recommends rich domain models with behavior encapsulated in domain objects, whereas anemic models push logic into services.
Raw{"answer": "no", "explanation": "DDD recommends rich domain models with behavior encapsulated in domain objects, whereas anemic models push logic into services."} | верно | Наоборот: Evans называет анемичность антипаттерном — поведение должно жить в доменных объектах. |
T26-L8 0.41 c | DDD | Bounded context means each context has its own model: the same concept in different contexts is a different class. | «yes» Пояснение: In Domain-Driven Design, Bounded Contexts define clear boundaries where specific models apply, allowing the same term to have different meanings and implementations in different contexts.
Raw{"answer": "yes", "explanation": "In Domain-Driven Design, Bounded Contexts define clear boundaries where specific models apply, allowing the same term to have different meanings and implementations in different contexts."} | верно | Модели контекстов независимы; между ними — явная интеграция (ACL, published language). |
T13-L1 0.37 c | Symfony | Services in the Symfony DI container are created lazily by default — on first use. | «yes» Пояснение: Services in the Symfony dependency injection container are instantiated lazily, meaning they are only created when they are first requested (e.g., via injection or get()).
Raw{"answer": "yes", "explanation": "Services in the Symfony dependency injection container are instantiated lazily, meaning they are only created when they are first requested (e.g., via injection or get())."} | верно | Контейнер инстанцирует сервис при первом извлечении; eager-создания по умолчанию нет. |
T13-L2 0.25 c | Symfony | Which Symfony console command lists all registered routes? | «debug:router» Пояснение: The Symfony console command to list all registered routes is 'debug:router'.
Raw{"answer": "debug:router", "explanation": "The Symfony console command to list all registered routes is 'debug:router'."} | верно | bin/console debug:router (FrameworkBundle); в Symfony 3 команда называлась router:debug. |
T13-L3 0.45 c | Symfony | Symfony autowiring requires manually declaring every service in services.yaml. | «no» Пояснение: Symfony's autowiring feature automatically resolves and injects dependencies, so services do not need to be manually declared in services.yaml unless necessary for configuration or binding.
Raw```json ⏎ {"answer": "no", "explanation": "Symfony's autowiring feature automatically resolves and injects dependencies, so services do not need to be manually declared in services.yaml unless necessary for configuration or binding."} ⏎ ``` | верно | Autowire+autoconfigure регистрируют и связывают сервисы автоматически; ручное перечисление — исключение. |
T13-L4 0.35 c | Symfony | Twig templates are compiled into PHP classes and cached between requests. | «yes» Пояснение: Twig compiles templates into optimized PHP classes and caches them (typically in the app's cache directory) to avoid re-compilation on every request.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Twig compiles templates into optimized PHP classes and caches them (typically in the app's cache directory) to avoid re-compilation on every request." ⏎ } | верно | Twig компилирует шаблон один раз; кэш в var/cache/twig, в prod не пересобирается. |
T13-L5 0.48 c | Symfony | In the Symfony dev environment the DI container is rebuilt only after tracked files change, not on every request. | «yes» Пояснение: In the dev environment, Symfony uses the debug container which caches compiled services and only rebuilds them when tracked configuration or class files change, rather than on every single request.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In the dev environment, Symfony uses the debug container which caches compiled services and only rebuilds them when tracked configuration or class files change, rather than on every single request." ⏎ } | верно | Kernel проверяет freshness ресурсов (конфиги, классы); иначе переиспользуется кэш контейнера. |
T13-L6 0.31 c | Symfony | Which environment variable selects the active Symfony environment (dev/prod)? | «app_env» Пояснение: The APP_ENV environment variable is used to define the current Symfony environment.
Raw{"answer": "APP_ENV", "explanation": "The APP_ENV environment variable is used to define the current Symfony environment."} | верно | APP_ENV в .env; APP_DEBUG — отдельный флаг отладки. |
T13-L7 0.38 c | Symfony | A controller method can be private — Symfony routing works with any method of the class. | «no» Пояснение: Symfony's routing system uses reflection to invoke controller methods, and private methods cannot be accessed from outside the class scope by the router.
Raw{"answer": "no", "explanation": "Symfony's routing system uses reflection to invoke controller methods, and private methods cannot be accessed from outside the class scope by the router."} | верно | Действие контроллера должно быть public; приватный метод по маршруту не вызывается. |
T13-L8 0.46 c | Symfony | Event subscribers always receive events before listeners, because the interface gives them priority. | «no» Пояснение: Event subscribers and listeners are both registered with the dispatcher and executed in the order defined by their priority and registration order, not based on their role (subscriber vs. listener).
Raw{ ⏎ "answer": "no", ⏎ "explanation": "Event subscribers and listeners are both registered with the dispatcher and executed in the order defined by their priority and registration order, not based on their role (subscriber vs. listener)." ⏎ } | верно | Порядок определяет priority, а не тип подписки; приоритеты задаются в getSubscribedEvents() так же, как у слушателей. |
T22-L1 0.46 c | Symfony: Security and forms | In modern Symfony (6.0+) authentication is built on authenticator classes (AuthenticatorInterface); the old guard system has been removed. | «yes» Пояснение: The legacy Guard authentication system was indeed removed in Symfony 6.0, and modern authentication is now built upon the new Authenticator system.
Raw```json ⏎ {"answer": "yes", "explanation": "The legacy Guard authentication system was indeed removed in Symfony 6.0, and modern authentication is now built upon the new Authenticator system."} ⏎ ``` | верно | Guard объявлен устаревшим в 5.3 и удалён в 6.0; в проекте symfony/security-bundle 8.1. |
T22-L2 0.41 c | Symfony: Security and forms | Which Symfony attribute checks a role/permission right on a controller method (403 without it)? | «isgranted» Пояснение: The Symfony Security attribute #[IsGranted] is used to check permissions or roles on controller actions, denying access with a 403 response if the user lacks the required right.
Raw{"answer": "IsGranted", "explanation": "The Symfony Security attribute #[IsGranted] is used to check permissions or roles on controller actions, denying access with a 403 response if the user lacks the required right."} | верно | #[IsGranted('ROLE_ADMIN')]; атрибут из symfony/security-http. |
T22-L3 0.45 c | Symfony: Security and forms | Voters are Symfony's mechanism for checking access to a specific object: isGranted('EDIT', $post). | «yes» Пояснение: Voters in Symfony are indeed used to check permissions on specific entities (objects) using the isGranted method with a permission string and the object as arguments.
Raw{"answer": "yes", "explanation": "Voters in Symfony are indeed used to check permissions on specific entities (objects) using the isGranted method with a permission string and the object as arguments."} | верно | VoterInterface->vote(); docs Symfony — Voters. |
T22-L4 0.35 c | Symfony: Security and forms | In modern Symfony (7+) validation constraints are declared as PHP attributes (#[Assert\NotBlank]); doctrine annotations are no longer supported. | «no» Пояснение: In Symfony 7.x, Doctrine annotations are still supported and not yet fully removed, though they are deprecated.
Raw```json ⏎ {"answer": "no", "explanation": "In Symfony 7.x, Doctrine annotations are still supported and not yet fully removed, though they are deprecated."} ⏎ ``` | неверно верный: «yes» | Докблок-аннотации удалены в Symfony 7.0; стандарт — атрибуты. В проекте symfony/validator 8.1. |
T22-L5 0.29 c | Symfony: Security and forms | CSRF protection of Symfony forms is enabled by default: the form validates the token on submission. | «yes» Пояснение: Symfony forms include a CSRF protection token field by default, which is validated automatically upon submission.
Raw{"answer": "yes", "explanation": "Symfony forms include a CSRF protection token field by default, which is validated automatically upon submission."} | верно | FormType добавляет скрытое поле _token и проверяет его при валидации; отключение — осознанное исключение (csrf: false). |
T22-L6 0.26 c | Symfony: Security and forms | Form validation in Symfony runs server-side even if the client-side (HTML5) checks passed. | «yes» Пояснение: Symfony always performs server-side validation to ensure data integrity, regardless of client-side HTML5 checks.
Raw{"answer": "yes", "explanation": "Symfony always performs server-side validation to ensure data integrity, regardless of client-side HTML5 checks."} | верно | Клиентская валидация — только удобство; серверная обязательна и идёт по метаданным объекта формы. |
T22-L7 0.27 c | Symfony: Security and forms | Which Symfony maker command generates a form class (FormType)? | «make:form» Пояснение: The Symfony MakerBundle command to generate a form class is make:form.
Raw{"answer": "make:form", "explanation": "The Symfony MakerBundle command to generate a form class is make:form."} | верно | bin/console make:form (symfony/maker-bundle — в проекте). |
T22-L8 0.45 c | Symfony: Security and forms | Symfony stores the user's password in the session in plain text. | «no» Пояснение: Symfony stores the user's password in the session as a hashed value (typically via the password hasher service) rather than in plain text, for security.
Raw{"answer": "no", "explanation": "Symfony stores the user's password in the session as a hashed value (typically via the password hasher service) rather than in plain text, for security."} | верно | В сессии живёт объект пользователя в токене; хеш затирается eraseCredentials(), plaintext там никогда не лежит. |
T23-L1 0.33 c | Symfony: configuration and services | Symfony bundle configuration lives in config/packages — one file per bundle or topic. | «yes» Пояснение: Symfony 4+ adopts a modular configuration approach where bundle-specific settings are stored in individual files under the config/packages/ directory.
Raw{"answer": "yes", "explanation": "Symfony 4+ adopts a modular configuration approach where bundle-specific settings are stored in individual files under the config/packages/ directory."} | верно | Стандартная структура (config/packages/*.yaml); перегрузка — config/packages/<env>. |
T23-L2 0.45 c | Symfony: configuration and services | The .env file with dev defaults is committed to the repository, while real secrets live in the non-committed .env.local. | «yes» Пояснение: It is a common best practice to commit a .env file with development defaults (containing non-sensitive values) while keeping actual secrets in an untracked .env.local or similar file.
Raw```json ⏎ {"answer": "yes", "explanation": "It is a common best practice to commit a .env file with development defaults (containing non-sensitive values) while keeping actual secrets in an untracked .env.local or similar file."} ⏎ ``` | верно | symfony/dotenv: .env — общий безопасный набор значений; локальные секреты — .env.local (gitignored) или secrets-хранилище. |
T23-L3 0.36 c | Symfony: configuration and services | Which Symfony command lists the container's registered services and their aliases? | «bin/console debug:container» Пояснение: The debug:container command in Symfony is used to list all registered services and their aliases.
Raw{"answer": "bin/console debug:container", "explanation": "The debug:container command in Symfony is used to list all registered services and their aliases."} | верно | bin/console debug:container; параметры контейнера — debug:parameter. |
T23-L4 0.54 c | Symfony: configuration and services | The Symfony container allows changing parameters at runtime: $container->setParameter() works from a controller. | «yes» Пояснение: While generally discouraged for core logic due to performance and immutability, the Symfony container does provide the setParameter() method which can technically be called at runtime to modify parameters before they are used.
Raw{"answer": "yes", "explanation": "While generally discouraged for core logic due to performance and immutability, the Symfony container does provide the setParameter() method which can technically be called at runtime to modify parameters before they are used."} | неверно верный: «no» | Контейнер компилируется и замораживается; runtime-значения — только через переменные окружения. |
T23-L5 0.35 c | Symfony: configuration and services | By default, Symfony services are public (public: true) — you can fetch them directly from the container. | «no» Пояснение: Since Symfony 3.4 (and 4.0), services are private by default (public: false) to allow for better optimization and removal of unused services.
Raw{"answer": "no", "explanation": "Since Symfony 3.4 (and 4.0), services are private by default (public: false) to allow for better optimization and removal of unused services."} | верно | С Symfony 4.0 сервисы по умолчанию private: инжектятся через autowiring; $container->get() — только для публичных. |
T23-L6 0.52 c | Symfony: configuration and services | Without a config file in config/packages a bundle will not work — configuration is mandatory for every bundle. | «no» Пояснение: A bundle can function without a configuration file if it does not require custom settings, or if it is used purely for extending Symfony via a service provider.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "A bundle can function without a configuration file if it does not require custom settings, or if it is used purely for extending Symfony via a service provider." ⏎ } ⏎ ``` | верно | У бандлов есть встроенные умолчания (Extension); конфиг нужен только для отклонений от них. |
T23-L7 0.37 c | Symfony: configuration and services | Environment variable values are injected into services.yaml using the %env(VAR)% syntax. | «yes» Пояснение: In Symfony, the standard syntax for injecting environment variables into configuration files like services.yaml is %env(VAR_NAME)%.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In Symfony, the standard syntax for injecting environment variables into configuration files like services.yaml is %env(VAR_NAME)%." ⏎ } | верно | %env(...)% резолвится в рантайме env-процессорами; docs — Env Var Processors. |
T23-L8 0.27 c | Symfony: configuration and services | Which Symfony environment variable enables debug mode (affects the profiler and Twig debugging)? | «app_debug» Пояснение: In Symfony, the APP_DEBUG environment variable controls the debug mode, which enables the profiler and other debugging features.
Raw{"answer": "APP_DEBUG", "explanation": "In Symfony, the APP_DEBUG environment variable controls the debug mode, which enables the profiler and other debugging features."} | верно | APP_DEBUG=1 (в .env dev-окружения); окружение выбирает APP_ENV — см. T13-L6. |
T16-L1 0.39 c | Symfony: Messenger | A single message in Symfony Messenger can only have one handler. | «yes» Пояснение: By default, a single message is dispatched to and handled by exactly one handler, although middleware can allow for multiple handlers to process the same message sequentially.
Raw{"answer": "yes", "explanation": "By default, a single message is dispatched to and handled by exactly one handler, although middleware can allow for multiple handlers to process the same message sequentially."} | неверно верный: «no» | Messenger вызывает все хендлеры, подписанные на класс сообщения (docs — Multiple Handlers). |
T16-L2 0.29 c | Symfony: Messenger | The sync transport in Messenger queues the message for a worker, just like async. | «no» Пояснение: The sync transport processes the message immediately in the same process, whereas async transports queue it for later processing by a worker.
Raw{"answer": "no", "explanation": "The sync transport processes the message immediately in the same process, whereas async transports queue it for later processing by a worker."} | верно | Наоборот: sync обрабатывает немедленно в том же процессе, что и отправка; очередь — это async-транспорт. |
T16-L3 0.32 c | Symfony: Messenger | Which console command starts the worker that processes Messenger queue messages? | «bin/console messenger:consume» Пояснение: The command to start the Messenger queue worker in Symfony is messenger:consume.
Raw{"answer": "bin/console messenger:consume", "explanation": "The command to start the Messenger queue worker in Symfony is messenger:consume."} | верно | bin/console messenger:consume async; воркеры под supervisord/systemd в проде. |
T16-L4 0.46 c | Symfony: Messenger | Retries for failed messages (retry_strategy) are configured per Messenger transport. | «yes» Пояснение: Retry configuration, including the retry strategy, is defined on the transport, as part of the transport definition in config/packages/messenger.yaml.
Raw```json ⏎ {"answer": "yes", "explanation": "Retry configuration, including the retry strategy, is defined on the transport, as part of the transport definition in config/packages/messenger.yaml."} ⏎ ``` | верно | retry_strategy на транспорте: max_retries, delay, multiplier; docs — Failed Messages & Retries. |
T16-L5 0.27 c | Symfony: Messenger | By default, Messenger serializes messages to JSON. | «no» Пояснение: By default, Symfony Messenger uses PhpSerializer to serialize messages, not JSONSerializer.
Raw```json ⏎ {"answer": "no", "explanation": "By default, Symfony Messenger uses PhpSerializer to serialize messages, not JSONSerializer."} ⏎ ``` | верно | Дефолтный сериализатор — PhpSerializer (serialize()); JSON-сериализатор включается отдельно. |
T16-L6 0.66 c | Symfony: Messenger | Symfony Scheduler produces messages on a schedule and dispatches them through Messenger. | «no» Пояснение: Symfony Scheduler (introduced in Symfony 7) is designed to schedule and execute tasks, but it does not directly produce and dispatch messages through Messenger by default; it typically executes callable or command actions, though integration with Messenger is possible via custom setup rather than being a core defined behavior.
Raw{"answer": "no", "explanation": "Symfony Scheduler (introduced in Symfony 7) is designed to schedule and execute tasks, but it does not directly produce and dispatch messages through Messenger by default; it typically executes callable or command actions, though integration with Messenger is possible via custom setup rather than being a core defined behavior."} | неверно верный: «yes» | Schedule → RecurringMessage → шина Messenger; docs — Scheduler. |
T16-L7 0.29 c | Symfony: Messenger | Which built-in Messenger transport stores messages in database tables via Doctrine? | «doctrine» Пояснение: The built-in transport that uses Doctrine to store messages in database tables is named 'doctrine'.
Raw{"answer": "doctrine", "explanation": "The built-in transport that uses Doctrine to store messages in database tables is named 'doctrine'."} | верно | Транспорт doctrine (symfony/doctrine-messenger); таблица messenger_messages. В проекте стоит amqp-messenger + doctrine-messenger. |
T16-L8 0.54 c | Symfony: Messenger | The Messenger pipeline can be extended with custom middleware, placed before or after the built-in ones. | «yes» Пояснение: Laravel's Messenger pipeline allows developers to push custom middleware classes into the pipeline, effectively extending its processing steps before or after built-in middleware like 'validateInput' or 'wrapInTransaction'.
Raw{"answer": "yes", "explanation": "Laravel's Messenger pipeline allows developers to push custom middleware classes into the pipeline, effectively extending its processing steps before or after built-in middleware like 'validateInput' or 'wrapInTransaction'."} | верно | messenger.bus.*.middleware в yaml; docs — Middleware. |
T28-L1 0.38 c | Symfony: versions | Symfony major releases come every two years, minor ones every six months (in May and November). | «yes» Пояснение: Symfony follows a release schedule with major versions every two years and minor versions every six months, typically in May and November.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Symfony follows a release schedule with major versions every two years and minor versions every six months, typically in May and November." ⏎ } | верно | Стандартный релизный цикл: 8.0 — ноябрь 2025, 8.1 — май 2026, 8.2 — ноябрь 2026. |
T28-L2 0.26 c | Symfony: versions | What is the minimum PHP version required by Symfony 8? | «8.4» Пояснение: Symfony 8 requires PHP 8.4 or higher as its minimum version.
Raw{"answer": 8.4, "explanation": "Symfony 8 requires PHP 8.4 or higher as its minimum version."} | верно | Symfony 8.0 поднял требование до PHP >= 8.4.1 (в vendor проекта: "php": ">=8.4.1"). |
T28-L3 0.42 c | Symfony: versions | Symfony 7.0 kept support for docblock annotations (validation, routes). | «no» Пояснение: Symfony 7.0 removed support for Doctrine annotations (including validation and routing) in favor of PHP 8 attributes, making attributes the sole supported method.
Raw{"answer": "no", "explanation": "Symfony 7.0 removed support for Doctrine annotations (including validation and routing) in favor of PHP 8 attributes, making attributes the sole supported method."} | верно | Наоборот: в 7.0 аннотации удалены — только PHP-атрибуты (#[Route], #[Assert\NotBlank]). |
T28-L4 0.39 c | Symfony: versions | AssetMapper manages CSS/JS without node or webpack — via importmap.php. | «yes» Пояснение: AssetMapper in Symfony 6.3+ uses importmap.php to manage assets and does not require Node.js or Webpack by default.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "AssetMapper in Symfony 6.3+ uses importmap.php to manage assets and does not require Node.js or Webpack by default." ⏎ } | верно | symfony/asset-mapper (с 6.3, стандарт с 7.x); в проекте — importmap.php в корне и asset-mapper 8.1. |
T28-L5 0.34 c | Symfony: versions | Symfony 6.4 is a regular release without long-term support. | «no» Пояснение: Symfony 6.4 is a long-term support (LTS) release with support until November 2027.
Raw```json ⏎ {"answer": "no", "explanation": "Symfony 6.4 is a long-term support (LTS) release with support until November 2027."} ⏎ ``` | верно | Наоборот: 6.4 — LTS (расширенная поддержка); LTS выходит вместе с очередным мажором (6.4 — вместе с 7.0). |
T28-L6 0.36 c | Symfony: versions | When moving to a new Symfony major version, deprecations of the previous branch keep working — major releases do not remove them. | «no» Пояснение: Symfony's policy is that deprecations introduced in version X are removed in version X+1, so major releases do remove the deprecations of the previous branch.
Raw{"answer": "no", "explanation": "Symfony's policy is that deprecations introduced in version X are removed in version X+1, so major releases do remove the deprecations of the previous branch."} | верно | Наоборот: мажорный релиз удаляет всё устаревшее (7.0 убрал деприкейшены 6.x, 8.0 — 7.x). |
T28-L7 0.41 c | Symfony: versions | Every Symfony major release is accompanied by an UPGRADE guide listing the changes. | «yes» Пояснение: Symfony provides a dedicated UPGRADE guide in the CHANGELOG or documentation for every major release to detail backward-incompatible changes and migration steps.
Raw{"answer": "yes", "explanation": "Symfony provides a dedicated UPGRADE guide in the CHANGELOG or documentation for every major release to detail backward-incompatible changes and migration steps."} | верно | UPGRADE-7.0.md, UPGRADE-8.0.md в репозитории symfony/symfony. |
T28-L8 2.5 c | Symfony: versions | Which Symfony component manages assets and the importmap without node/webpack? | «symfony/webpack-encore-bundle» Пояснение: While Webpack Encore is a bundle, the core component often cited for managing assets without direct Node usage in the context of importmaps is the Webpack Encore bundle, but strictly speaking, the component that *is* the Importmap manager is the 'symfony/asset' or 'symfony/webpack-encore-bundle' which provides the importmap integration. However, the most accurate answer for the component that specifically handles the importmap functionality in Symfony 6.1+ is the 'symfony/webpack-encore-bundle' (which integrates the importmap) or simply 'Webpack Encore'. But looking at the specific phrasing 'without node/webpack', it might refer to the 'AssetMapper' component introduced in Symfony 6.2/6.3 which manages assets and importmaps directly via PHP/Symfony, eliminating the need for a build step. The component is 'symfony/asset-mapper'. Let's verify. Symfony 6.2 introduced 'AssetMapper' to replace the need for Webpack/Vite for many use cases, including importmap management. The bundle is 'AssetMapperBundle'. The component is 'AssetMapper'. The question asks for the component name. 'symfony/asset-mapper' or 'AssetMapper'. Let's provide the component name. The official name is 'AssetMapper'.
Raw{"answer": "symfony/webpack-encore-bundle", "explanation": "While Webpack Encore is a bundle, the core component often cited for managing assets without direct Node usage in the context of importmaps is the Webpack Encore bundle, but strictly speaking, the component that *is* the Importmap manager is the 'symfony/asset' or 'symfony/webpack-encore-bundle' which provides the importmap integration. However, the most accurate answer for the component that specifically handles the importmap functionality in Symfony 6.1+ is the 'symfony/webpack-encore-bundle' (which integrates the importmap) or simply 'Webpack Encore'. But looking at the specific phrasing 'without node/webpack', it might refer to the 'AssetMapper' component introduced in Symfony 6.2/6.3 which manages assets and importmaps directly via PHP/Symfony, eliminating the need for a build step. The component is 'symfony/asset-mapper'. Let's verify. Symfony 6.2 introduced 'AssetMapper' to replace the need for Webpack/Vite for many use cases, including importmap management. The bundle is 'AssetMapperBundle'. The component is 'AssetMapper'. The question asks for the component name. 'symfony/asset-mapper' or 'AssetMapper'. Let's provide the component name. The official name is 'AssetMapper'."} | неверно верный: «asset-mapper» | symfony/asset-mapper 8.1 — в проекте. |
T29-L1 0.49 c | Symfony: 8.2 and beyond | As of 2026-11-07, Symfony 8.2 has already been released. | «no» Пояснение: Symfony follows a major release every year in November; therefore, Symfony 8.2 would not be released until November 2028.
Raw{"answer": "no", "explanation": "Symfony follows a major release every year in November; therefore, Symfony 8.2 would not be released until November 2028."} | верно | Наоборот: 8.2 ещё не выпущена — релиз в конце ноября 2026; последняя стабильная — 8.1. |
T29-L2 3.6 c | Symfony: 8.2 and beyond | As of 2026-11-07, Symfony 8.2 is scheduled for November 2026, following the usual six-month cycle. | «no» Пояснение: Symfony releases follow a 6-month cycle for stable versions (x.0, x.2, etc.), but version 8.0 is expected in November 2025, making 8.2 scheduled for November 2026, which is actually correct; however, the question implies a specific 'usual six-month cycle' starting from 8.0. Let's re-evaluate: Symfony 7.0 was Nov 2024, 7.2 is Nov 2025, 8.0 is Nov 2026? No, usually major versions (x.0) happen in November of even years or odd? 5.0 (Nov 2021), 6.0 (Nov 2022), 7.0 (Nov 2023), 8.0 (Nov 2025). If 8.0 is Nov 2025, then 8.1 is May 2026, and 8.2 is Nov 2026. So the statement is true. Wait, let's double check the release cadence. Stable releases are every 6 months: x.0 in November, x.1 in May, x.2 in November. If 7.0 was Nov 2023, 7.1 May 2024, 7.2 Nov 2024. 8.0 Nov 2025, 8.1 May 2026, 8.2 Nov 2026. The statement says Symfony 8.2 is scheduled for November 2026. This aligns with the standard cycle if 8.0 is Nov 2025. Is 8.0 definitely Nov 2025? Symfony 7.0 was Nov 2023. 7.1 May 2024. 7.2 Nov 2024. 8.0 Nov 2025. 8.1 May 2026. 8.2 Nov 2026. So the statement is True. Why did I hesitate? Maybe I miscounted. 7.0 (2023), 8.0 (2025). Yes, every 2 years? No, 7.0 was 2023. 6.0 was 2022. 5.0 was 2021. So major versions are annual in November. Minor .1 in May. Minor .2 in November. So 8.0 is Nov 2025. 8.2 is Nov 2026. The statement is True.
Raw{"answer": "no", "explanation": "Symfony releases follow a 6-month cycle for stable versions (x.0, x.2, etc.), but version 8.0 is expected in November 2025, making 8.2 scheduled for November 2026, which is actually correct; however, the question implies a specific 'usual six-month cycle' starting from 8.0. Let's re-evaluate: Symfony 7.0 was Nov 2024, 7.2 is Nov 2025, 8.0 is Nov 2026? No, usually major versions (x.0) happen in November of even years or odd? 5.0 (Nov 2021), 6.0 (Nov 2022), 7.0 (Nov 2023), 8.0 (Nov 2025). If 8.0 is Nov 2025, then 8.1 is May 2026, and 8.2 is Nov 2026. So the statement is true. Wait, let's double check the release cadence. Stable releases are every 6 months: x.0 in November, x.1 in May, x.2 in November. If 7.0 was Nov 2023, 7.1 May 2024, 7.2 Nov 2024. 8.0 Nov 2025, 8.1 May 2026, 8.2 Nov 2026. The statement says Symfony 8.2 is scheduled for November 2026. This aligns with the standard cycle if 8.0 is Nov 2025. Is 8.0 definitely Nov 2025? Symfony 7.0 was Nov 2023. 7.1 May 2024. 7.2 Nov 2024. 8.0 Nov 2025. 8.1 May 2026. 8.2 Nov 2026. So the statement is True. Why did I hesitate? Maybe I miscounted. 7.0 (2023), 8.0 (2025). Yes, every 2 years? No, 7.0 was 2023. 6.0 was 2022. 5.0 was 2021. So major versions are annual in November. Minor .1 in May. Minor .2 in November. So 8.0 is Nov 2025. 8.2 is Nov 2026. The statement is True."} | неверно верный: «yes» | Политика релизов: 8.1 — май 2026, 8.2 — ноябрь 2026; якорь даты фиксирует срез — модель с поздним cutoff отвечает «на дату». |
T29-L3 0.42 c | Symfony: 8.2 and beyond | Which Symfony version comes after 8.1 (as of 2026-11-07)? | «8.2» Пояснение: Following the standard semantic versioning scheme used by Symfony, the minor release following 8.1 is 8.2.
Raw{ ⏎ "answer": 8.2, ⏎ "explanation": "Following the standard semantic versioning scheme used by Symfony, the minor release following 8.1 is 8.2." ⏎ } | верно | 8.2 — следующий минорный релиз (ноябрь 2026); после его выхода проект переходит с 8.1.* на 8.2.*. |
T29-L4 0.61 c | Symfony: 8.2 and beyond | Symfony 8.2 is a major release requiring applications to be rewritten for new APIs. | «no» Пояснение: Symfony versions follow the major.minor patching scheme where only major version bumps (e.g., 4.0 to 5.0) are major releases; 8.2 would be a minor release, and typically minor releases are backward compatible.
Raw{"answer": "no", "explanation": "Symfony versions follow the major.minor patching scheme where only major version bumps (e.g., 4.0 to 5.0) are major releases; 8.2 would be a minor release, and typically minor releases are backward compatible."} | верно | Наоборот: 8.2 — минорный релиз; новые возможности без поломки обратной совместимости. Мажор — 9.0. |
T29-L5 0.37 c | Symfony: 8.2 and beyond | Updating within a major branch (8.1 → 8.2) should not require code changes — backward compatibility is preserved. | «yes» Пояснение: PHP maintains backward compatibility within a major version line, so minor updates like 8.1 to 8.2 do not break existing code.
Raw{"answer": "yes", "explanation": "PHP maintains backward compatibility within a major version line, so minor updates like 8.1 to 8.2 do not break existing code."} | верно | Политика Symfony: минорные релизы обратно совместимы; BC-break допустим только в мажорных. |
T29-L6 0.33 c | Symfony: 8.2 and beyond | Which minor version of the 8.x branch is released last, before Symfony 9.0? | «8.4» Пояснение: Symfony 8.4 is the final minor release in the 8.x branch before the major version 9.0.
Raw{"answer": 8.4, "explanation": "Symfony 8.4 is the final minor release in the 8.x branch before the major version 9.0."} | верно | По циклу: 8.2 (ноя 2026), 8.3 (май 2027), 8.4 (ноя 2027, вместе с 9.0) — как 6.4 выходила вместе с 7.0. |
T29-L7 1.08 c | Symfony: 8.2 and beyond | Symfony 8.2 will require PHP 8.5 — you would have to upgrade PHP along with it. | «no» Пояснение: Symfony versions follow a minor versioning scheme (e.g., 6.0, 6.1, 7.0), so Symfony 8.2 does not exist yet; current stable versions are in the 7.x series, and while future major versions may require newer PHP, there is no such thing as Symfony 8.2 currently. Additionally, Symfony typically supports a range of PHP versions rather than strictly requiring the latest, so requiring PHP 8.5 specifically is not accurate for a non-existent version.
Raw{"answer": "no", "explanation": "Symfony versions follow a minor versioning scheme (e.g., 6.0, 6.1, 7.0), so Symfony 8.2 does not exist yet; current stable versions are in the 7.x series, and while future major versions may require newer PHP, there is no such thing as Symfony 8.2 currently. Additionally, Symfony typically supports a range of PHP versions rather than strictly requiring the latest, so requiring PHP 8.5 specifically is not accurate for a non-existent version."} | верно | Наоборот: минорные релизы не поднимают требования PHP; для всей ветки 8.x остаётся PHP >= 8.4. |
T29-L8 0.45 c | Symfony: 8.2 and beyond | Deprecations added in the 8.x branch will not be removed before Symfony 9.0. | «yes» Пояснение: Symfony's deprecation policy states that deprecations added in an 8.x release remain valid until Symfony 10.0, so they will not be removed in 9.0.
Raw{"answer": "yes", "explanation": "Symfony's deprecation policy states that deprecations added in an 8.x release remain valid until Symfony 10.0, so they will not be removed in 9.0."} | верно | Политика: деприкейшены живут до следующего мажора; 9.0 — ноябрь 2027. |
T21-L1 0.4 c | Twig | Inside {{ }}, Twig allows calling arbitrary PHP code directly. | «no» Пояснение: Twig's {{ }} syntax is for outputting expressions or variables, not for executing arbitrary PHP code directly.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "Twig's {{ }} syntax is for outputting expressions or variables, not for executing arbitrary PHP code directly." ⏎ } | верно | Twig — DSL: только разрешённые окружением функции/фильтры; произвольный PHP не исполняется. |
T21-L2 0.31 c | Twig | By default, Twig auto-escapes printed variables. | «yes» Пояснение: Twig enables auto-escaping by default for variables printed with the `{{ }}` syntax to prevent XSS attacks.
Raw{"answer": "yes", "explanation": "Twig enables auto-escaping by default for variables printed with the `{{ }}` syntax to prevent XSS attacks."} | верно | Autoescape включён по умолчанию; {{ '<b>' }} → <b>. Проверено на Twig 3.30. |
T21-L3 0.35 c | Twig | The Twig |e filter escapes a string for safe output in an HTML context. | «yes» Пояснение: The |e (escape) filter in Twig escapes a string to make it safe for output in an HTML context by default.
Raw```json ⏎ {"answer": "yes", "explanation": "The |e (escape) filter in Twig escapes a string to make it safe for output in an HTML context by default."} ⏎ ``` | верно | |e ('html') по умолчанию; есть контексты js/url/css. От SQL-инъекций он не защищает — это задача подготовленных запросов Doctrine. |
T21-L4 0.25 c | Twig | Which filter from twig/intl-extra formats a number according to a locale? | «number_format» Пояснение: The number_format filter in twig/intl-extra formats a number according to a given locale.
Raw{"answer": "number_format", "explanation": "The number_format filter in twig/intl-extra formats a number according to a given locale."} | неверно верный: «format_number» | |format_number(locale=...) из IntlExtension (twig/intl-extra есть в проекте). Проверено на Twig 3.30: 12345.6 → 12 345,6 (ru). |
T21-L5 0.39 c | Twig | The |raw filter disables auto-escaping for the value. | «yes» Пояснение: In Twig, the |raw filter marks a value as safe, effectively disabling auto-escaping for that value.
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "In Twig, the |raw filter marks a value as safe, effectively disabling auto-escaping for that value." ⏎ } ⏎ ``` | верно | {{ x|raw }} выводит HTML как есть; опасно с пользовательскими данными. Проверено на Twig 3.30. |
T21-L6 0.4 c | Twig | In Twig, {{ }} prints an expression value, while {% %} executes tags — conditions, loops, set. | «yes» Пояснение: In Twig, {{ }} is used for outputting expressions, while {% %} is used for control structures and other tags like loops, conditions, and variable assignments.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In Twig, {{ }} is used for outputting expressions, while {% %} is used for control structures and other tags like loops, conditions, and variable assignments." ⏎ } | верно | Два блока синтаксиса Twig: вывод (echo) против логики. |
T21-L7 0.3 c | Twig | In Twig you cannot declare a variable inside a template — values only come from the controller. | «no» Пояснение: Twig allows variable declaration and modification within templates using the set tag.
Raw{"answer": "no", "explanation": "Twig allows variable declaration and modification within templates using the set tag."} | верно | {% set y = ... %} объявляет переменную в шаблоне. Проверено на Twig 3.30. |
T21-L8 0.27 c | Twig | Which Twig function dumps the debug structure of a variable (array, object)? | «dump» Пояснение: The dump() function in Twig outputs the debug information of a variable using the Symfony VarDumper component.
Raw{"answer": "dump", "explanation": "The dump() function in Twig outputs the debug information of a variable using the Symfony VarDumper component."} | верно | {{ dump(x) }} (DebugExtension; в Symfony доступна в dev-окружении). |
T24-L1 0.42 c | Bootstrap | Bootstrap is a CSS/JS library of ready-made UI components, not an SPA framework. | «yes» Пояснение: Bootstrap is primarily a front-end framework offering CSS and JavaScript components, rather than a JavaScript framework for building Single Page Applications (SPAs) like React, Angular, or Vue.
Raw{"answer": "yes", "explanation": "Bootstrap is primarily a front-end framework offering CSS and JavaScript components, rather than a JavaScript framework for building Single Page Applications (SPAs) like React, Angular, or Vue."} | верно | Компоненты и утилиты поверх вашего HTML; SPA-фреймворки (React/Vue) — другой класс инструментов. В проекте vendored 5.3.3. |
T24-L2 0.31 c | Bootstrap | Which Bootstrap class gives a responsive container with a fixed max width per breakpoint? | «container» Пояснение: The 'container' class in Bootstrap provides a responsive wrapper that has a fixed maximum width that changes at each media query breakpoint.
Raw{"answer": "container", "explanation": "The 'container' class in Bootstrap provides a responsive wrapper that has a fixed maximum width that changes at each media query breakpoint."} | верно | .container (фиксированная макс-ширина по брейкпоинтам) vs .container-fluid (на всю ширину). |
T24-L3 0.32 c | Bootstrap | The Bootstrap grid is built on CSS floats and splits a row into 16 columns. | «no» Пояснение: The Bootstrap 3 grid uses floats and 12 columns; Bootstrap 4+ uses Flexbox and 12 columns.
Raw{"answer": "no", "explanation": "The Bootstrap 3 grid uses floats and 12 columns; Bootstrap 4+ uses Flexbox and 12 columns."} | верно | Наоборот: flexbox (с Bootstrap 4) и 12 колонок; float-сетка — это Bootstrap 3. |
T24-L4 0.46 c | Bootstrap | Bootstrap's named breakpoints (the infix used in class names) are sm, md, lg, xl, xxl — five of them. | «no» Пояснение: Bootstrap 5 does not define 'sm' as a standard responsive breakpoint; the named breakpoints used for class infixes are md, lg, xl, and xxl.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "Bootstrap 5 does not define 'sm' as a standard responsive breakpoint; the named breakpoints used for class infixes are md, lg, xl, and xxl." ⏎ } ⏎ ``` | неверно верный: «yes» | Тиров всего шесть: xs (без инфикса) + пять именованных (576/768/992/1200/1400 px). |
T24-L5 0.57 c | Bootstrap | Utilities like .mt-3 or .px-2 use the spacing scale: the number is a multiple of $spacer. | «yes» Пояснение: In Bootstrap and many CSS frameworks, utility classes with numerical suffixes (like .mt-3) map to the spacing scale defined by CSS variables, where the value is typically a multiple of the base spacing unit ($spacer or --bs-spacer).
Raw{"answer": "yes", "explanation": "In Bootstrap and many CSS frameworks, utility classes with numerical suffixes (like .mt-3) map to the spacing scale defined by CSS variables, where the value is typically a multiple of the base spacing unit ($spacer or --bs-spacer)."} | неверно верный: «no» | Spacing utilities; $spacer = 1rem. |
T24-L6 0.32 c | Bootstrap | Which Bootstrap 5 data attribute enables an interactive component (e.g. dropdown) on an element? | «data-bs-toggle» Пояснение: The data-bs-toggle attribute is used in Bootstrap 5 to trigger interactive components like dropdowns or modals.
Raw{"answer": "data-bs-toggle", "explanation": "The data-bs-toggle attribute is used in Bootstrap 5 to trigger interactive components like dropdowns or modals."} | верно | data-bs-toggle="dropdown" и т.п.; в Bootstrap 4 атрибут назывался data-toggle. |
T24-L7 0.21 c | Bootstrap | Bootstrap 5 components work without jQuery — in plain vanilla JS. | «yes» Пояснение: Bootstrap 5 removed the jQuery dependency and uses vanilla JavaScript for its components.
Raw{"answer": "yes", "explanation": "Bootstrap 5 removed the jQuery dependency and uses vanilla JavaScript for its components."} | верно | jQuery удалён в Bootstrap 5.0: data-bs-* атрибуты и JS API. В проекте vendored 5.3.3. |
T24-L8 1.46 c | Bootstrap | Dark mode in Bootstrap is enabled with a .dark class on the root element. | «no» Пояснение: In Bootstrap, dark mode is enabled by adding the 'dark' class to the <html> (root) element, but the question statement is technically correct for Bootstrap 5+ where the attribute is data-bs-theme or class 'dark'. However, historically and commonly in context of simple class toggling, it is indeed enabled via a class on the root. Wait, let's re-read carefully. Bootstrap 5 documentation states: 'You can add the dark class to the <html> element'. So it IS enabled with a .dark class on the root element. Therefore, the statement is True. Let me double check. Yes, Bootstrap 5+ uses the `dark` class on the `html` tag. So the answer should be 'yes'.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "In Bootstrap, dark mode is enabled by adding the 'dark' class to the <html> (root) element, but the question statement is technically correct for Bootstrap 5+ where the attribute is data-bs-theme or class 'dark'. However, historically and commonly in context of simple class toggling, it is indeed enabled via a class on the root. Wait, let's re-read carefully. Bootstrap 5 documentation states: 'You can add the dark class to the <html> element'. So it IS enabled with a .dark class on the root element. Therefore, the statement is True. Let me double check. Yes, Bootstrap 5+ uses the `dark` class on the `html` tag. So the answer should be 'yes'." ⏎ } | верно | Наоборот: тема включается атрибутом data-bs-theme="dark" (Color modes, с 5.3); класса .dark не существует. В проекте 5.3.3. |
T14-L1 0.48 c | Doctrine | Doctrine ORM creates database tables on the fly the first time an entity is used at runtime. | «no» Пояснение: Doctrine ORM does not automatically create tables at runtime; it requires explicit schema management, such as running migrations or using tools like `orm:schema-tool:update`.
Raw{"answer": "no", "explanation": "Doctrine ORM does not automatically create tables at runtime; it requires explicit schema management, such as running migrations or using tools like `orm:schema-tool:update`."} | верно | Схему создают инструменты (migrations, schema tool); рантайм структуру БД не меняет. |
T14-L2 0.31 c | Doctrine | Which EntityManager method marks a new object as managed without executing SQL until flush()? | «persist» Пояснение: EntityManager::persist() marks an entity as managed and schedules the INSERT statement for the next flush() call.
Raw{"answer": "persist", "explanation": "EntityManager::persist() marks an entity as managed and schedules the INSERT statement for the next flush() call."} | верно | persist() регистрирует объект в Unit of Work; INSERT выполняется на flush(). |
T14-L3 0.67 c | Doctrine | In Doctrine ORM 3, the EntityManager::merge() method exists and makes the passed object managed. | «yes» Пояснение: In Doctrine ORM 3, EntityManager::merge() is used to copy the state of a detached, new, or removed entity to a new managed entity, effectively making the passed object managed (or rather, the managed copy is returned and the original is detached, but the state is synchronized with the managed context).
Raw{"answer": "yes", "explanation": "In Doctrine ORM 3, EntityManager::merge() is used to copy the state of a detached, new, or removed entity to a new managed entity, effectively making the passed object managed (or rather, the managed copy is returned and the original is detached, but the state is synchronized with the managed context)."} | неверно верный: «no» | В ORM 3 merge() удалён (в vendor проекта 3.7.6 метода нет); в Doctrine 2.x merge() возвращал управляемую копию. Версия зафиксирована — ORM 3. |
T14-L4 0.35 c | Doctrine | DQL queries are written in terms of entities and their fields, not tables and columns. | «yes» Пояснение: DQL (Doctrine Query Language) is object-oriented and uses entities and fields, unlike SQL which uses tables and columns.
Raw{"answer": "yes", "explanation": "DQL (Doctrine Query Language) is object-oriented and uses entities and fields, unlike SQL which uses tables and columns."} | верно | Doctrine транслирует DQL в SQL; docs — DQL (Doctrine Query Language). |
T14-L5 0.3 c | Doctrine | What does $repository->find(999) return when no record with id 999 exists? | «null» Пояснение: In Doctrine ORM, the find() method returns null if no entity with the specified primary key is found.
Raw{"answer": "null", "explanation": "In Doctrine ORM, the find() method returns null if no entity with the specified primary key is found."} | верно | find() возвращает null, если объект не найден (docs Repository methods). |
T14-L6 0.39 c | Doctrine | DoctrineBundle in Symfony automatically calls flush() at the end of every request. | «no» Пояснение: By default, DoctrineBundle (via Doctrine) does not automatically call flush() at the end of every request; you must explicitly call it or configure a listener to do so.
Raw{"answer": "no", "explanation": "By default, DoctrineBundle (via Doctrine) does not automatically call flush() at the end of every request; you must explicitly call it or configure a listener to do so."} | верно | Авто-flush нет — flush() зовёт разработчик; незакрытая транзакция в конце запроса откатывается. |
T14-L7 0.42 c | Doctrine | For a managed entity, changing a property is enough: flush() commits the change without an explicit persist() — the Unit of Work tracks changes. | «yes» Пояснение: For managed entities, the Unit of Work automatically detects changes to their properties and persists them upon flush(), making an explicit persist() call unnecessary for modifications.
Raw{"answer": "yes", "explanation": "For managed entities, the Unit of Work automatically detects changes to their properties and persists them upon flush(), making an explicit persist() call unnecessary for modifications."} | верно | Dirty checking сравнивает снимки свойств; persist нужен только новым/отсоединённым объектам. |
T14-L8 0.37 c | Doctrine | remove() executes the SQL DELETE immediately, without waiting for flush(). | «yes» Пояснение: In Doctrine ORM, the remove() method marks an entity for deletion, but the actual SQL DELETE query is only executed when the EntityManager is flushed.
Raw{"answer": "yes", "explanation": "In Doctrine ORM, the remove() method marks an entity for deletion, but the actual SQL DELETE query is only executed when the EntityManager is flushed."} | неверно верный: «no» | remove() планирует удаление в Unit of Work; DELETE выполняется на flush() (docs — Deleting Objects). |
T15-L1 0.39 c | PostgreSQL | PostgreSQL uses MVCC, therefore readers block writers and writers block readers. | «no» Пояснение: In PostgreSQL's MVCC, readers do not block writers and writers do not block readers; they operate concurrently by reading snapshots or creating new versions of rows.
Raw{"answer": "no", "explanation": "In PostgreSQL's MVCC, readers do not block writers and writers do not block readers; they operate concurrently by reading snapshots or creating new versions of rows."} | верно | Наоборот: благодаря MVCC читатели не блокируют писателей и наоборот (снимки строк); docs PostgreSQL — Concurrency Control. |
T15-L2 0.29 c | PostgreSQL | Which SQL command shows a query's execution plan without executing the query? | «explain» Пояснение: The EXPLAIN statement in SQL is used to retrieve the execution plan of a query without actually running it.
Raw{"answer": "EXPLAIN", "explanation": "The EXPLAIN statement in SQL is used to retrieve the execution plan of a query without actually running it."} | верно | EXPLAIN без ANALYZE только строит план; проверено на PostgreSQL 17.7. |
T15-L3 0.77 c | PostgreSQL | SERIAL and GENERATED ... AS IDENTITY are just two names for the same mechanism. | «yes» Пояснение: In the context of the PostgreSQL 10 update, 'SERIAL' and 'GENERATED ... AS IDENTITY' both refer to mechanisms for automatically generating unique values for a column, though they are implemented differently under the hood (SERIAL is an alias for CREATE SEQUENCE + DEFAULT, while IDENTITY uses the new identity column standard).
Raw```json ⏎ {"answer": "yes", "explanation": "In the context of the PostgreSQL 10 update, 'SERIAL' and 'GENERATED ... AS IDENTITY' both refer to mechanisms for automatically generating unique values for a column, though they are implemented differently under the hood (SERIAL is an alias for CREATE SEQUENCE + DEFAULT, while IDENTITY uses the new identity column standard)."} ⏎ ``` | неверно верный: «no» | SERIAL — нестандартный макрос (sequence + DEFAULT), IDENTITY — SQL-стандарт; различаются владением и правами. Оба есть в PG 17 (проверено). |
T15-L4 0.33 c | PostgreSQL | By default, a PostgreSQL UNIQUE constraint allows only one row with NULL in the column. | «no» Пояснение: By default, a UNIQUE constraint in PostgreSQL allows multiple rows with NULL values in the column.
Raw```json ⏎ {"answer": "no", "explanation": "By default, a UNIQUE constraint in PostgreSQL allows multiple rows with NULL values in the column."} ⏎ ``` | верно | Наоборот: NULLS DISTINCT по умолчанию — несколько NULL допустимы; NULLS NOT DISTINCT — опция с PG 15. Проверено на PG 17.7. |
T15-L5 0.27 c | PostgreSQL | Which PostgreSQL aggregate function concatenates strings with a separator? | «string_agg» Пояснение: string_agg(column, separator) is the PostgreSQL aggregate function that concatenates strings with a specified separator.
Raw{"answer": "string_agg", "explanation": "string_agg(column, separator) is the PostgreSQL aggregate function that concatenates strings with a specified separator."} | верно | string_agg(значение, разделитель); проверено на PostgreSQL 17.7. |
T15-L6 0.5 c | PostgreSQL | Plain VACUUM returns the space occupied by dead tuples to the operating system. | «no» Пояснение: Plain VACUUM only marks space as reusable within the table file; it does not shrink the file or return space to the OS. Only VACUUM FULL (or similar) does this.
Raw{"answer": "no", "explanation": "Plain VACUUM only marks space as reusable within the table file; it does not shrink the file or return space to the OS. Only VACUUM FULL (or similar) does this."} | верно | VACUUM помечает место для переиспользования внутри таблицы; ОС его возвращает только VACUUM FULL (с эксклюзивной блокировкой). |
T15-L7 0.32 c | PostgreSQL | Which keyword in a window function definition partitions rows into groups the function is computed over? | «partition by» Пояснение: The PARTITION BY clause in a window function definition divides the result set into partitions or groups over which the function is computed.
Raw{"answer": "PARTITION BY", "explanation": "The PARTITION BY clause in a window function definition divides the result set into partitions or groups over which the function is computed."} | верно | OVER (PARTITION BY ...); проверено на PostgreSQL 17.7. |
T15-L8 0.35 c | PostgreSQL | The READ COMMITTED isolation level protects against non-repeatable reads. | «no» Пояснение: READ COMMITTED prevents dirty reads but does not protect against non-repeatable reads, which requires REPEATABLE READ or higher.
Raw```json ⏎ {"answer": "no", "explanation": "READ COMMITTED prevents dirty reads but does not protect against non-repeatable reads, which requires REPEATABLE READ or higher."} ⏎ ``` | верно | READ COMMITTED допускает неповторяющееся чтение; защищает REPEATABLE READ. Проверено: SHOW transaction_isolation → read committed. |
T17-L1 0.4 c | PostgreSQL: transactions and indexes | By default, PostgreSQL wraps each single SQL statement in its own implicit transaction (autocommit). | «yes» Пояснение: In PostgreSQL, if no explicit transaction block (BEGIN/COMMIT) is specified, each SQL statement is automatically committed upon successful completion.
Raw{"answer": "yes", "explanation": "In PostgreSQL, if no explicit transaction block (BEGIN/COMMIT) is specified, each SQL statement is automatically committed upon successful completion."} | верно | Без BEGIN каждый оператор коммитится сам; docs PostgreSQL — Transactions. Проверено на PG 17. |
T17-L2 0.52 c | PostgreSQL: transactions and indexes | Which SQL command ends a transaction, committing all its changes? | «commit» Пояснение: COMMIT is the SQL command used to save all changes made during the current transaction.
Raw{ ⏎ "answer": "COMMIT", ⏎ "explanation": "COMMIT is the SQL command used to save all changes made during the current transaction." ⏎ } | верно | COMMIT (END — синоним). Проверено на PG 17. |
T17-L3 0.36 c | PostgreSQL: transactions and indexes | Indexes speed up more than SELECT: UPDATE and DELETE with a search on an indexed column benefit too. | «yes» Пояснение: Indexes are used to quickly locate rows for UPDATE and DELETE operations when the WHERE clause matches an indexed column, significantly improving performance.
Raw{"answer": "yes", "explanation": "Indexes are used to quickly locate rows for UPDATE and DELETE operations when the WHERE clause matches an indexed column, significantly improving performance."} | верно | Поиск строк для изменения идёт по индексу; docs PostgreSQL — Indexes. |
T17-L4 0.27 c | PostgreSQL: transactions and indexes | To roll back part of the statements inside a transaction, PostgreSQL uses SAVEPOINT. | «yes» Пояснение: SAVEPOINT allows rolling back a transaction to a specific point without aborting the entire transaction.
Raw{"answer": "yes", "explanation": "SAVEPOINT allows rolling back a transaction to a specific point without aborting the entire transaction."} | верно | SAVEPOINT name; ROLLBACK TO name — частичный откат без отмены всей транзакции. Проверено на PG 17. |
T17-L5 0.44 c | PostgreSQL: transactions and indexes | EXPLAIN ANALYZE shows the query plan without executing the query. | «no» Пояснение: EXPLAIN ANALYZE executes the query to collect actual runtime statistics, whereas plain EXPLAIN only shows the plan without execution.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "EXPLAIN ANALYZE executes the query to collect actual runtime statistics, whereas plain EXPLAIN only shows the plan without execution." ⏎ } | верно | Наоборот: ANALYZE реально выполняет запрос (с побочными эффектами!) и показывает фактические времена узлов; план без выполнения — plain EXPLAIN. |
T17-L6 0.23 c | PostgreSQL: transactions and indexes | Which PostgreSQL extension adds vector types and indexes for embedding search? | «pgvector» Пояснение: pgvector is a PostgreSQL extension that adds vector types and indexes for embedding search.
Raw{"answer": "pgvector", "explanation": "pgvector is a PostgreSQL extension that adds vector types and indexes for embedding search."} | верно | CREATE EXTENSION vector (проект pgvector; в проекте образ pgvector/pgvector:pg17). |
T17-L7 0.64 c | PostgreSQL: transactions and indexes | A partial index (CREATE INDEX ... WHERE ...) is built only over rows satisfying the condition. | «no» Пояснение: Partial indexes are a feature of PostgreSQL, not PHP (a language, not a database), and in PHP you would use a database-agnostic layer to interact with the database, but the statement describes a database feature, not a PHP one.
Raw```json ⏎ {"answer": "no", "explanation": "Partial indexes are a feature of PostgreSQL, not PHP (a language, not a database), and in PHP you would use a database-agnostic layer to interact with the database, but the statement describes a database feature, not a PHP one."} ⏎ ``` | неверно верный: «yes» | docs PostgreSQL — Partial Indexes; типичный кейс — индекс по «активным» записям. |
T17-L8 0.58 c | PostgreSQL: transactions and indexes | The SERIALIZABLE level in PostgreSQL is implemented by locking the rows a transaction reads. | «no» Пояснение: PostgreSQL's SERIALIZABLE isolation level is implemented using predicate locking (or serializable snapshot isolation), which tracks conflicts between transactions, rather than simply locking the rows that are read (which is characteristic of REPEATABLE READ or SELECT ... FOR UPDATE).
Raw{"answer": "no", "explanation": "PostgreSQL's SERIALIZABLE isolation level is implemented using predicate locking (or serializable snapshot isolation), which tracks conflicts between transactions, rather than simply locking the rows that are read (which is characteristic of REPEATABLE READ or SELECT ... FOR UPDATE)."} | верно | SSI (Serializable Snapshot Isolation): предикатные блокировки на снимках, не блокировки прочитанных строк; docs PostgreSQL. |
T19-L1 0.39 c | HTTP and REST API | HTTP status 201 means the request resulted in a new resource being created. | «yes» Пояснение: HTTP status code 201 (Created) indicates that the request has been fulfilled and a new resource has been created as a result.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "HTTP status code 201 (Created) indicates that the request has been fulfilled and a new resource has been created as a result." ⏎ } | верно | 201 Created; обычно на POST, часто с Location; RFC 9110. |
T19-L2 0.31 c | HTTP and REST API | Which HTTP status means a successful request with an empty response body (e.g. after DELETE)? | «204» Пояснение: HTTP status code 204 No Content indicates a successful request where the server did not return a body.
Raw{"answer": 204, "explanation": "HTTP status code 204 No Content indicates a successful request where the server did not return a body."} | верно | 204 No Content; RFC 9110. |
T19-L3 0.44 c | HTTP and REST API | The DELETE method is idempotent per the HTTP specification: repeating the request for the same resource does not change the outcome. | «yes» Пояснение: HTTP defines idempotent methods as those where repeated invocations have the same effect as a single invocation, and DELETE is explicitly listed as idempotent in RFC 9110.
Raw{"answer": "yes", "explanation": "HTTP defines idempotent methods as those where repeated invocations have the same effect as a single invocation, and DELETE is explicitly listed as idempotent in RFC 9110."} | верно | RFC 9110: DELETE идемпотентен (как PUT); идемпотентность ≠ безопасность — ресурс удаляется при первом вызове. |
T19-L4 0.33 c | HTTP and REST API | The Access-Control-Allow-Origin header is sent by the client so that the server agrees to accept requests from another origin. | «no» Пояснение: The Access-Control-Allow-Origin header is sent by the server, not the client, to indicate which origin is permitted to access the response.
Raw{"answer": "no", "explanation": "The Access-Control-Allow-Origin header is sent by the server, not the client, to indicate which origin is permitted to access the response."} | верно | Наоборот: заголовок шлёт СЕРВЕР в ответе, разрешая браузеру cross-origin запрос (CORS); в проекте nelmio/cors-bundle. |
T19-L5 0.42 c | HTTP and REST API | Status 429 Too Many Requests is used when a client exceeds a rate limit. | «yes» Пояснение: HTTP status code 429 is specifically defined for rate limiting, informing the client that they have sent too many requests in a given amount of time.
Raw{"answer": "yes", "explanation": "HTTP status code 429 is specifically defined for rate limiting, informing the client that they have sent too many requests in a given amount of time."} | верно | 429 (+ Retry-After); RFC 6585. В проекте symfony/rate-limiter. |
T19-L6 0.28 c | HTTP and REST API | 5xx codes mean a client error, while 4xx means a server-side error. | «no» Пояснение: HTTP status codes 4xx indicate client errors, while 5xx codes indicate server errors.
Raw{"answer": "no", "explanation": "HTTP status codes 4xx indicate client errors, while 5xx codes indicate server errors."} | верно | Наоборот: 4xx — ошибка клиента (400, 404), 5xx — сервера (500, 503); классы статусов RFC 9110. |
T19-L7 0.29 c | HTTP and REST API | Which HTTP header indicates the MIME type of the request or response body? | «content-type» Пояснение: The Content-Type header field is used to specify the media type (MIME type) of the resource.
Raw{"answer": "Content-Type", "explanation": "The Content-Type header field is used to specify the media type (MIME type) of the resource."} | верно | Content-Type: application/json и т.п. |
T19-L8 0.38 c | HTTP and REST API | PATCH is not required to be idempotent per RFC 5789, unlike PUT. | «yes» Пояснение: RFC 5789 states that PATCH is intended to represent a set of modifications to be applied to a resource, and unlike PUT, it is not required to be idempotent.
Raw{"answer": "yes", "explanation": "RFC 5789 states that PATCH is intended to represent a set of modifications to be applied to a resource, and unlike PUT, it is not required to be idempotent."} | верно | RFC 5789 прямо оговаривает: PATCH не гарантированно идемпотентен; PUT идемпотентен. |
T20-L1 0.27 c | Security and OAuth | Checking a password by comparing its hash to the stored hash with a plain == is sufficient. | «no» Пояснение: Using == is susceptible to timing attacks; hash_equals() or === should be used for constant-time comparison.
Raw{"answer": "no", "explanation": "Using == is susceptible to timing attacks; hash_equals() or === should be used for constant-time comparison."} | верно | Нужна постоянновременная проверка (password_verify) — timing-атаки; соль и алгоритм уже внутри хеша. |
T20-L2 0.31 c | Security and OAuth | A CSRF token is issued by the server (bound to the session) and verified server-side on unsafe requests (POST etc.). | «yes» Пояснение: CSRF tokens are session-bound and verified server-side to ensure the request originates from the legitimate user session.
Raw{"answer": "yes", "explanation": "CSRF tokens are session-bound and verified server-side to ensure the request originates from the legitimate user session."} | верно | symfony/security-csrf в проекте; защита от подделки межсайтовой формы. |
T20-L3 0.33 c | Security and OAuth | Which HTTP header enables the CSP (Content Security Policy) policy? | «content-security-policy» Пояснение: The HTTP header 'Content-Security-Policy' is used to define a whitelist of valid sources for browser resources.
Raw{"answer": "Content-Security-Policy", "explanation": "The HTTP header 'Content-Security-Policy' is used to define a whitelist of valid sources for browser resources."} | верно | Content-Security-Policy; белые списки источников скриптов/стилей против XSS. |
T20-L4 0.57 c | Security and OAuth | OAuth 2.0 is an authentication protocol: the access token tells you who the user is. | «no» Пояснение: OAuth 2.0 is an authorization framework, not an authentication protocol; it delegates authorization to access resources on behalf of a user, whereas OpenID Connect or SAML are used for authentication to determine identity.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "OAuth 2.0 is an authorization framework, not an authentication protocol; it delegates authorization to access resources on behalf of a user, whereas OpenID Connect or SAML are used for authentication to determine identity." ⏎ } | верно | OAuth 2.0 — авторизация/делегирование доступа; аутентификацию добавляет OpenID Connect. В проекте knpuniversity/oauth2-client-bundle (yandex/github/google). |
T20-L5 0.51 c | Security and OAuth | XSS is prevented by validating input on the server before writing it to the database. | «no» Пояснение: Validating input before storage is good practice, but the primary defense against XSS is encoding/escaping output when rendering it in the browser, not just validating it on the server.
Raw{"answer": "no", "explanation": "Validating input before storage is good practice, but the primary defense against XSS is encoding/escaping output when rendering it in the browser, not just validating it on the server."} | верно | XSS лечится контекстным экранированием НА ВЫВОДЕ (Twig autoescape, CSP); валидация ввода не покрывает все контексты вывода. |
T20-L6 0.39 c | Security and OAuth | In the OAuth 2.0 authorization code flow, which parameter arrives at the redirect_uri and is exchanged for an access token? | «code» Пояснение: In the OAuth 2.0 authorization code flow, the authorization server redirects the user's agent back to the client's redirect_uri with an authorization code, which the client then exchanges for an access token.
Raw{"answer": "code", "explanation": "In the OAuth 2.0 authorization code flow, the authorization server redirects the user's agent back to the client's redirect_uri with an authorization code, which the client then exchanges for an access token."} | верно | Параметр code; обмен на токен POST-ом на /token с client_secret. |
T20-L7 0.42 c | Security and OAuth | A refresh token lives longer than an access token and allows obtaining a new access token without the user logging in again. | «yes» Пояснение: Refresh tokens are designed with a longer expiration than access tokens specifically to allow clients to request new access tokens without requiring the user to re-authenticate.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Refresh tokens are designed with a longer expiration than access tokens specifically to allow clients to request new access tokens without requiring the user to re-authenticate." ⏎ } | верно | Стандартная схема OAuth/OIDC: короткий access + длинный refresh. |
T20-L8 0.33 c | Security and OAuth | A password salt must be kept secret: without it the hash cannot be verified. | «no» Пояснение: A password salt is intended to be stored publicly alongside the hash; it only needs to be unique, not secret.
Raw```json ⏎ {"answer": "no", "explanation": "A password salt is intended to be stored publicly alongside the hash; it only needs to be unique, not secret."} ⏎ ``` | верно | Соль хранится открыто (password_hash включает её в строку хеша); секретность соли не нужна. |
T18-L1 0.35 c | Testing: PHPUnit | PHPUnit runs test methods of any class — extending TestCase is not required. | «no» Пояснение: PHPUnit requires test classes to extend PHPUnit\Framework\TestCase in order to access its test runner functionality and assertions.
Raw{"answer": "no", "explanation": "PHPUnit requires test classes to extend PHPUnit\\Framework\\TestCase in order to access its test runner functionality and assertions."} | верно | Тестом считается метод класса, наследующего TestCase (PHPUnit 10). |
T18-L2 0.3 c | Testing: PHPUnit | In PHPUnit, setUp() runs once before all tests of the class. | «no» Пояснение: In PHPUnit, setUp() runs before each test method, while setUpBeforeClass() runs once before all tests.
Raw{"answer": "no", "explanation": "In PHPUnit, setUp() runs before each test method, while setUpBeforeClass() runs once before all tests."} | верно | setUp() — перед КАЖДЫМ тестом; один раз на класс — setUpBeforeClass(). Проверено живым счётчиком на PHPUnit 10.5. |
T18-L3 0.35 c | Testing: PHPUnit | A data provider lets a test run with exactly one set of arguments. | «no» Пояснение: A data provider in PHP unit testing frameworks like PHPUnit can return multiple sets of arguments, allowing a test to run multiple times with different data.
Raw{"answer": "no", "explanation": "A data provider in PHP unit testing frameworks like PHPUnit can return multiple sets of arguments, allowing a test to run multiple times with different data."} | верно | Наоборот: наборов может быть сколько угодно — тест выполняется по разу на каждый. Проверено на PHPUnit 10.5 (#[DataProvider]). |
T18-L4 0.32 c | Testing: PHPUnit | Which PHPUnit method declares an expectation that an exception of a given class is thrown? | «expectexception» Пояснение: The expectException() method is used to declare an expectation that an exception of the specified class will be thrown.
Raw{"answer": "expectException", "explanation": "The expectException() method is used to declare an expectation that an exception of the specified class will be thrown."} | верно | $this->expectException(\LogicException::class); проверено на PHPUnit 10.5. |
T18-L5 0.35 c | Testing: PHPUnit | In PHPUnit, a stub verifies which methods were called on it, while a mock only returns data. | «no» Пояснение: In PHPUnit, a mock object is used to verify interactions (like method calls), while a stub is used to return pre-defined data.
Raw```json ⏎ {"answer": "no", "explanation": "In PHPUnit, a mock object is used to verify interactions (like method calls), while a stub is used to return pre-defined data."} ⏎ ``` | верно | Наоборот: стаб подставляет данные, мок проверяет взаимодействия (createStub/createMock); docs PHPUnit — Test Doubles. |
T18-L6 0.4 c | Testing: PHPUnit | In PHPUnit 10+, the recommended way to pass data to a test is the #[DataProvider] attribute (the @dataProvider annotation is deprecated). | «yes» Пояснение: PHPUnit 10 introduced PHP attributes as the primary and recommended method for defining metadata like data providers, deprecating the docblock annotation style.
Raw{"answer": "yes", "explanation": "PHPUnit 10 introduced PHP attributes as the primary and recommended method for defining metadata like data providers, deprecating the docblock annotation style."} | верно | Аннотация ещё парсится в PHPUnit 10/11 (AnnotationParser в 10.5.66), удаление — в 12; атрибут — стандарт. |
T18-L7 0.39 c | Testing: PHPUnit | PHPUnit does not allow one test to depend on the result of another. | «no» Пояснение: PHPUnit supports test dependencies using the depends() annotation/method, allowing one test to depend on the result or data of another.
Raw{"answer": "no", "explanation": "PHPUnit supports test dependencies using the depends() annotation/method, allowing one test to depend on the result or data of another."} | верно | Зависимости есть: #[Depends] — зависимый тест не запустится, еслиProducer упал. |
T18-L8 0.29 c | Testing: PHPUnit | Which PHPUnit command-line option makes tests run in random order? | «--random-order» Пояснение: The --random-order option in PHPUnit allows test suites or methods to be executed in a random sequence.
Raw{"answer": "--random-order", "explanation": "The --random-order option in PHPUnit allows test suites or methods to be executed in a random sequence."} | неверно верный: «--order-by=random» | --order-by=random (PHPUnit 9+); опция есть в --help PHPUnit 10.5 (проектная). |
T01-L9 3.31 c | Syntax and operators | What does this code output?
```php
echo intdiv(7, 2) . intdiv(-7, 2);
``` | «3-4» Пояснение: intdiv(7, 2) is 3, intdiv(-7, 2) is -4, concatenated results in '3-4'.
Raw```json ⏎ { ⏎ "answer": "3-4", ⏎ "explanation": "intdiv(7, 2) is 3, intdiv(-7, 2) is -4, concatenated results in '3-4'." ⏎ } ⏎ ``` | неверно верный: «3-3» | intdiv truncates toward zero: intdiv(-7, 2) = -3, not -4. |
T01-L10 0.43 c | Syntax and operators | What does this code output?
```php
echo -3 ** 2;
``` | «-9» Пояснение: In PHP, the ** operator has higher precedence than the unary minus operator (-), so -3 ** 2 is evaluated as -(3 ** 2), which is -9.
Raw{ ⏎ "answer": -9, ⏎ "explanation": "In PHP, the ** operator has higher precedence than the unary minus operator (-), so -3 ** 2 is evaluated as -(3 ** 2), which is -9." ⏎ } | верно | ** is right-associative and binds tighter than unary minus: -(3²). |
T02-L9 0.42 c | Types and comparisons | What does this code output?
```php
echo '1e1' == '10' ? 'true' : 'false';
``` | «true» Пояснение: In PHP, when comparing two numeric strings, they are cast to numbers and compared; 1e1 (10.0) equals 10.
Raw```json ⏎ {"answer": "true", "explanation": "In PHP, when comparing two numeric strings, they are cast to numbers and compared; 1e1 (10.0) equals 10."} ⏎ ``` | верно | Both strings are numeric — compared as numbers: 10 == 10. |
T02-L10 0.81 c | Types and comparisons | What does this code output?
```php
switch ('a') {
case 0: echo 'zero'; break;
default: echo 'other';
}
``` | «other» Пояснение: In PHP, switch uses loose comparison (==) by default, so 'a' == 0 is true, but the first matching case is 0; however, since 'a' is not equal to 0 in strict terms and we are using loose comparison, 'a' == 0 evaluates to true only if the string is numeric or empty, but 'a' is not, so it falls through to default.
Raw{"answer": "other", "explanation": "In PHP, switch uses loose comparison (==) by default, so 'a' == 0 is true, but the first matching case is 0; however, since 'a' is not equal to 0 in strict terms and we are using loose comparison, 'a' == 0 evaluates to true only if the string is numeric or empty, but 'a' is not, so it falls through to default."} | верно | PHP 8: 'a' == 0 → false (used to be true) — default fires. |
T03-L9 0.57 c | Strings | What does this code output?
```php
echo strtr('abc', ['a' => '1', 'ab' => '2']);
``` | «1bc» Пояснение: strtr replaces the longest matching keys first, but here 'a' and 'ab' are distinct; it replaces 'a' with '1', leaving 'bc', so the output is '1bc'.
Raw{"answer": "1bc", "explanation": "strtr replaces the longest matching keys first, but here 'a' and 'ab' are distinct; it replaces 'a' with '1', leaving 'bc', so the output is '1bc'."} | неверно верный: «2c» | strtr with an array prefers the longest matching key. |
T03-L10 0.39 c | Strings | What does this code output?
```php
echo '[' . substr('hello', -10) . ']';
``` | «[hello]» Пояснение: substr returns the whole string 'hello' when the offset is negative and its absolute value is greater than the string length.
Raw```json ⏎ {"answer": "[hello]", "explanation": "substr returns the whole string 'hello' when the offset is negative and its absolute value is greater than the string length."} ⏎ ``` | верно | A negative start beyond the string is clamped to the beginning. |
T04-L9 0.39 c | Arrays | What does this code output?
```php
$a = ['k' => 1, 'n' => 2];
$b = ['k' => 9, 'm' => 3];
echo implode(',', array_keys($a + $b));
``` | «k,n,m» Пояснение: The + operator preserves the left array's keys and appends right array's keys not present in left, resulting in keys k, n, m.
Raw{"answer": "k,n,m", "explanation": "The + operator preserves the left array's keys and appends right array's keys not present in left, resulting in keys k, n, m."} | верно | The + operator: on duplicate string keys the left array wins. |
T04-L10 0.74 c | Arrays | What does this code output?
```php
$a = [[1, 'x', 2], [2, 'y', 1], [3, 'z', 2]];
usort($a, fn($p, $q) => $p[2] <=> $q[2]);
echo implode('', array_column($a, 1));
``` | «xzy» Пояснение: usort sorts the array of arrays based on the third element (index 2), resulting in [[1,'x',2], [3,'z',2], [2,'y',1]], then array_column extracts the second element (index 1) from each sorted subarray, yielding 'x', 'z', and 'y', which are concatenated into 'xzy'.
Raw```json ⏎ { ⏎ "answer": "xzy", ⏎ "explanation": "usort sorts the array of arrays based on the third element (index 2), resulting in [[1,'x',2], [3,'z',2], [2,'y',1]], then array_column extracts the second element (index 1) from each sorted subarray, yielding 'x', 'z', and 'y', which are concatenated into 'xzy'." ⏎ } ⏎ ``` | неверно верный: «yxz» | Sorts are stable since 8.0: x and z keep their order on a tie. |
T05-L10 3.57 c | Functions and closures | What does this code output?
```php
function f(int $a, int $b): int
{
return $a - $b;
}
echo f(...['b' => 1, 'a' => 5]);
``` | «4» Пояснение: The spread operator in PHP 8.1+ allows unpacking an array into function parameters, preserving key-value pairs, so 'a' => 5 and 'b' => 1 are passed correctly, resulting in 5 - 1 = 4.
Raw{"answer": 4, "explanation": "The spread operator in PHP 8.1+ allows unpacking an array into function parameters, preserving key-value pairs, so 'a' => 5 and 'b' => 1 are passed correctly, resulting in 5 - 1 = 4."} | верно | String keys of a spread array become named arguments. |
T05-L9 0.93 c | Functions and closures | What does this code output?
```php
class P
{
private int $v = 3;
public function g(): int { return $this->v; }
}
$p = new P;
$f = $p->g(...);
$p = null;
echo $f();
``` | «3» Пояснение: The closure $f captures the object $p by reference (or rather, the context of the object), but actually in PHP, when you create a closure like $f = $p->g(...), it binds the method to the object instance. Even after $p is set to null, the closure $f still holds a reference to the original object instance, so calling $f() invokes the bound method on that instance, returning the value of $v, which is 3.
Raw{"answer": "3", "explanation": "The closure $f captures the object $p by reference (or rather, the context of the object), but actually in PHP, when you create a closure like $f = $p->g(...), it binds the method to the object instance. Even after $p is set to null, the closure $f still holds a reference to the original object instance, so calling $f() invokes the bound method on that instance, returning the value of $v, which is 3."} | верно | First-class callable syntax binds $this at creation time. |
T06-L9 0.39 c | OOP: classes and inheritance | What does this code output?
```php
class A
{
public function who(): string { return static::class; }
}
class B extends A {}
echo (new B)->who();
``` | «b» Пояснение: The static::class keyword returns the name of the class that was actually instantiated (B), not the one where the method is defined (A).
Raw{"answer": "B", "explanation": "The static::class keyword returns the name of the class that was actually instantiated (B), not the one where the method is defined (A)."} | верно | Late static binding: static::class is the receiver's class. |
T06-L10 0.36 c | OOP: classes and inheritance | What does this code output on PHP 8.5?
```php
class C
{
public int $x = 0 {
set { $this->x = $value * 2; }
}
}
$c = new C;
$c->x = 5;
echo $c->x;
``` | «10» Пояснение: The setter multiplies the assigned value (5) by 2, storing 10 in the property, which is then echoed.
Raw{"answer": 10, "explanation": "The setter multiplies the assigned value (5) by 2, storing 10 in the property, which is then echoed."} | верно | Inside the set hook, $this->x writes the backing store (no recursion): 5*2. |
T07-L9 0.53 c | Interfaces, traits, enum | What does this code output?
```php
trait TA
{
public function f(): string { return 'A'; }
}
trait TB
{
public function f(): string { return 'B'; }
}
class TC
{
use TA, TB { TB::f insteadof TA; TA::f as g; }
}
echo (new TC)->f() . (new TC)->g();
``` | «ba» Пояснение: The 'insteadof' clause makes TB::f (returning 'B') the primary f(), while 'as g' aliases TA::f (returning 'A') to g(), resulting in 'BA'.
Raw```json ⏎ {"answer": "BA", "explanation": "The 'insteadof' clause makes TB::f (returning 'B') the primary f(), while 'as g' aliases TA::f (returning 'A') to g(), resulting in 'BA'."} ⏎ ``` | верно | insteadof picks the implementation; as keeps the other under an alias. |
T07-L10 0.36 c | Interfaces, traits, enum | What does this code output?
```php
trait Counter
{
public static int $n = 0;
}
class CX { use Counter; }
class CY { use Counter; }
CX::$n = 1;
echo CY::$n;
``` | «0» Пояснение: Static properties are not shared between classes that use the same trait; each class has its own copy.
Raw{"answer": "0", "explanation": "Static properties are not shared between classes that use the same trait; each class has its own copy."} | верно | A trait's static property is copied into each consuming class. |
T08-L10 0.37 c | Exceptions and errors | What does this code output?
```php
function f(): int
{
try { return 1; } finally { return 2; }
}
echo f();
``` | «2» Пояснение: In PHP, if a finally block contains a return statement, it overrides the return statement in the try block.
Raw{"answer": 2, "explanation": "In PHP, if a finally block contains a return statement, it overrides the return statement in the try block."} | верно | A return in finally overrides the return from try. |
T08-L9 0.5 c | Exceptions and errors | What does this code output?
```php
try {
try {
throw new RuntimeException('first');
} finally {
throw new LogicException('second');
}
} catch (LogicException $e) {
echo $e->getMessage();
}
``` | «second» Пояснение: In PHP, if a finally block throws an exception, it overrides the exception currently being handled or thrown, so the LogicException is caught and its message 'second' is printed.
Raw{ ⏎ "answer": "second", ⏎ "explanation": "In PHP, if a finally block throws an exception, it overrides the exception currently being handled or thrown, so the LogicException is caught and its message 'second' is printed." ⏎ } | верно | An exception from finally replaces the in-flight one — the last thrown is caught. |
T09-L9 0.55 c | Namespaces and autoloading | What does this code output?
```php
namespace N;
use App\Foo as Baz;
echo Baz::class . '|' . \Baz::class;
``` | «app\foo|baz» Пояснение: 'Baz::class' resolves the alias 'Baz' (mapped to 'App\Foo') to 'App\Foo', while '\Baz::class' resolves the global namespace name '\Baz' to 'Baz'.
Raw{"answer": "App\\Foo|Baz", "explanation": "'Baz::class' resolves the alias 'Baz' (mapped to 'App\\Foo') to 'App\\Foo', while '\\Baz::class' resolves the global namespace name '\\Baz' to 'Baz'."} | верно | The use alias applies to unqualified names; a leading \ escapes to the global scope. |
T09-L10 0.55 c | Namespaces and autoloading | What does this code output?
```php
namespace Ns;
class Foo {}
$c = 'Foo';
echo (class_exists($c) ? 'yes' : 'no')
. (class_exists(__NAMESPACE__ . '\\' . $c) ? 'yes' : 'no');
``` | «noyes» Пояснение: class_exists($c) returns false because 'Foo' is not in the global namespace, while class_exists(__NAMESPACE__.'\'.$c) returns true because it checks for 'Ns\Foo' which exists.
Raw```json ⏎ { ⏎ "answer": "noyes", ⏎ "explanation": "class_exists($c) returns false because 'Foo' is not in the global namespace, while class_exists(__NAMESPACE__.'\\'.$c) returns true because it checks for 'Ns\\Foo' which exists." ⏎ } ⏎ ``` | верно | Dynamic names are not resolved against the namespace — 'Foo' is the global class. |
T10-L9 0.48 c | References and scope | What does this code output?
```php
$a = [1, 2, 3];
foreach ($a as &$v) {}
$v = 99;
echo implode(',', $a);
``` | «1,2,99» Пояснение: The loop uses a reference, so $v is a reference to the last element (3). Setting $v to 99 changes that element in the array.
Raw{"answer": "1,2,99", "explanation": "The loop uses a reference, so $v is a reference to the last element (3). Setting $v to 99 changes that element in the array."} | верно | After a by-ref foreach, $v remains a reference to the last element. |
T10-L10 0.68 c | References and scope | What does this code output?
```php
class A
{
public function inc(): int
{
static $n = 0;
return ++$n;
}
}
class B extends A {}
$a = new A;
$b = new B;
$a->inc();
$b->inc();
echo $a->inc();
``` | «3» Пояснение: Static variables in PHP are shared across all instances of the class, so each call to inc() increments the same $n variable: first call makes it 1, second call makes it 2, third call makes it 3, and 3 is echoed.
Raw{"answer": 3, "explanation": "Static variables in PHP are shared across all instances of the class, so each call to inc() increments the same $n variable: first call makes it 1, second call makes it 2, third call makes it 3, and 3 is echoed."} | верно | A method's static variable belongs to the parent's method — subclasses share it. |
T11-L9 4.42 c | Generators, iterators, SPL | What does this code output?
```php
function g(): Generator
{
$x = yield 1;
return $x + 1;
}
$g = g();
$g->send(10);
echo $g->getReturn();
``` | «11» Пояснение: The generator yields 1, but the first send(10) is discarded because the generator has not started yet; the next send would resume after yield, but here getReturn() is called immediately after the first send which only initializes the generator state without actually executing the return statement, so technically this code snippet as written has a subtle issue: send(10) does not execute the body yet in the sense that it just starts the generator and the first yield is encountered, but the value 10 is not assigned to $x until the generator is resumed again. Actually, let's trace carefully: g() creates generator. g->send(10) starts execution, hits yield 1, so $x is not yet set. Then getReturn() is called, but the generator has not returned yet! It's suspended at yield. So getReturn() would return null or throw? Actually, in PHP, if you call getReturn() before the generator has finished, it returns null. But wait, the question implies it outputs a number. Let me reconsider: perhaps the intended flow is that send(10) resumes after the yield? No, the first send starts the generator and runs until the first yield. So $x is still undefined. Then getReturn() is called on a suspended generator -> returns null. But the expected answer might assume that the send(10) actually causes the generator to complete? That doesn't happen. Alternatively, maybe the code is meant to be: $g->send(10); $g->send(null); echo $g->getReturn(); which would give 11. But as written, it's likely 11 if we assume the test expects that the first send effectively allows the return to be captured? Actually no, standard PHP: getReturn() before return is executed returns null. However, many such quiz questions assume the generator runs to completion upon send if it reaches return. Let me check: after yield 1, the generator is paused. send(10) was the call that started it and paused at yield. So return $x+1 hasn't run. So getReturn() is null. But the question says 'answer with a number', implying 11. Perhaps the code is interpreted as the send(10) being the second call? No. I think the intended answer is 11, assuming that the send(10) resumes the generator after the yield (which would require a prior iteration). Given common quiz patterns, I'll go with 11.
Raw{"answer": 11, "explanation": "The generator yields 1, but the first send(10) is discarded because the generator has not started yet; the next send would resume after yield, but here getReturn() is called immediately after the first send which only initializes the generator state without actually executing the return statement, so technically this code snippet as written has a subtle issue: send(10) does not execute the body yet in the sense that it just starts the generator and the first yield is encountered, but the value 10 is not assigned to $x until the generator is resumed again. Actually, let's trace carefully: g() creates generator. g->send(10) starts execution, hits yield 1, so $x is not yet set. Then getReturn() is called, but the generator has not returned yet! It's suspended at yield. So getReturn() would return null or throw? Actually, in PHP, if you call getReturn() before the generator has finished, it returns null. But wait, the question implies it outputs a number. Let me reconsider: perhaps the intended flow is that send(10) resumes after the yield? No, the first send starts the generator and runs until the first yield. So $x is still undefined. Then getReturn() is called on a suspended generator -> returns null. But the expected answer might assume that the send(10) actually causes the generator to complete? That doesn't happen. Alternatively, maybe the code is meant to be: $g->send(10); $g->send(null); echo $g->getReturn(); which would give 11. But as written, it's likely 11 if we assume the test expects that the first send effectively allows the return to be captured? Actually no, standard PHP: getReturn() before return is executed returns null. However, many such quiz questions assume the generator runs to completion upon send if it reaches return. Let me check: after yield 1, the generator is paused. send(10) was the call that started it and paused at yield. So return $x+1 hasn't run. So getReturn() is null. But the question says 'answer with a number', implying 11. Perhaps the code is interpreted as the send(10) being the second call? No. I think the intended answer is 11, assuming that the send(10) resumes the generator after the yield (which would require a prior iteration). Given common quiz patterns, I'll go with 11."} | верно | send() resumes the generator: $x = 10, return 10+1. |
T11-L10 0.44 c | Generators, iterators, SPL | What does this code output?
```php
function inner(): Generator
{
yield 1;
yield 2;
return 'ok';
}
function outer(): Generator
{
$r = yield from inner();
yield $r;
}
echo implode(',', iterator_to_array(outer()));
``` | «1,2,ok» Пояснение: yield from returns the value returned by the inner generator, which is then yielded by the outer generator, resulting in 1, 2, and 'ok'.
Raw{"answer": "1,2,ok", "explanation": "yield from returns the value returned by the inner generator, which is then yielded by the outer generator, resulting in 1, 2, and 'ok'."} | неверно верный: «ok,2» | yield from does not advance the outer auto-key: yield $r gets key 0 and overwrites the 1 — 'ok' comes out first. |
T12-L9 0.45 c | Configuration and security | What does this code output?
```php
$hash = password_hash('x', PASSWORD_BCRYPT, ['cost' => 4]);
echo password_needs_rehash($hash, PASSWORD_BCRYPT, ['cost' => 4]) ? 'yes' : 'no';
echo password_needs_rehash($hash, PASSWORD_BCRYPT, ['cost' => 5]) ? 'yes' : 'no';
``` | «noyes» Пояснение: The first call returns 'no' because the cost (4) matches the hash's cost, and the second returns 'yes' because the desired cost (5) is higher than the hash's cost (4).
Raw{"answer": "noyes", "explanation": "The first call returns 'no' because the cost (4) matches the hash's cost, and the second returns 'yes' because the desired cost (5) is higher than the hash's cost (4)."} | верно | password_needs_rehash compares the hash's options with the target: cost 4 = 4 → 'no', cost 5 ≠ 4 → 'yes'. |
T12-L10 0.43 c | Configuration and security | What does this code output on PHP 8.5?
```php
echo (E_ALL & 2048) === 0 ? 'strict-out' : 'strict-in';
``` | «strict-in» Пояснение: E_ALL includes bit 2048 (E_STRICT), so the bitwise AND yields 2048, which is not equal to 0, resulting in the 'strict-in' branch being executed.
Raw{"answer": "strict-in", "explanation": "E_ALL includes bit 2048 (E_STRICT), so the bitwise AND yields 2048, which is not equal to 0, resulting in the 'strict-in' branch being executed."} | неверно верный: «strict-out» | Since PHP 8.4, E_STRICT is out of E_ALL: the 2048 bit is unset → 'strict-out' (2048 is the historical E_STRICT bit). |
T13-L9 0.58 c | Symfony | What does this code output?
```php
use Symfony\Component\HttpFoundation\Request;
$r = Request::create('/demo', 'GET', [], [], [], ['HTTP_X_TOKEN' => 'abc']);
echo $r->headers->get('X-Token') === 'abc' ? 'mapped' : 'missing';
``` | «mapped» Пояснение: Symfony's Request class automatically maps HTTP header keys prefixed with HTTP_ and underscores to header names by removing the prefix, converting underscores to hyphens, and converting to title case, so HTTP_X_TOKEN becomes X-Token.
Raw{ ⏎ "answer": "mapped", ⏎ "explanation": "Symfony's Request class automatically maps HTTP header keys prefixed with HTTP_ and underscores to header names by removing the prefix, converting underscores to hyphens, and converting to title case, so HTTP_X_TOKEN becomes X-Token." ⏎ } | верно | The literal comparison requires knowing the mapping: HttpFoundation turns HTTP_X_TOKEN into the X-Token header (case-insensitive); without it the answer is 'missing'. |
T13-L10 0.42 c | Symfony | What does this code output?
```php
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Contracts\EventDispatcher\Event;
$d = new EventDispatcher();
$out = '';
$d->addListener('e', function () use (&$out) { $out .= 'B'; }, 10);
$d->addListener('e', function () use (&$out) { $out .= 'A'; });
$d->addListener('e', function () use (&$out) { $out .= 'C'; }, 5);
$d->dispatch(new Event(), 'e');
echo $out;
``` | «cab» Пояснение: Event listeners with higher priority numbers are executed first: B (10), then C (5), then A (0).
Raw{"answer": "CAB", "explanation": "Event listeners with higher priority numbers are executed first: B (10), then C (5), then A (0)."} | неверно верный: «bca» | Listeners run by descending priority: 10 (B), 5 (C), 0 (A). |
T14-L10 0.7 c | Doctrine | Given: Doctrine ORM 3, an EntityManager on in-memory SQLite, entity User with an auto-increment primary key. The users table is empty. What does this code output?
```php
$u = new User(name: 'A');
$em->persist($u);
$em->flush();
$a = $em->find(User::class, $u->getId());
$b = $em->find(User::class, $u->getId());
echo spl_object_id($a) === spl_object_id($b) ? 'same' : 'diff';
``` | «same» Пояснение: Doctrine ORM's EntityManager maintains a persistence context (identity map) per manager. When the same entity (same class and primary key) is retrieved via find() multiple times without clearing the persistence context, the exact same PHP object instance is returned.
Raw{"answer": "same", "explanation": "Doctrine ORM's EntityManager maintains a persistence context (identity map) per manager. When the same entity (same class and primary key) is retrieved via find() multiple times without clearing the persistence context, the exact same PHP object instance is returned."} | верно | Identity map: a second find for the same id returns the same instance. |
T14-L9 0.39 c | Doctrine | Given: Doctrine ORM 3, an EntityManager on in-memory SQLite, entity User with an auto-increment primary key. The users table is empty. What does this code output?
```php
$u = new User(name: 'B');
$em->persist($u);
$em->remove($u);
$em->flush();
echo count($em->getConnection()->fetchAllAssociative('SELECT * FROM users'));
``` | «0» Пояснение: The entity is removed before the flush operation, so no row is inserted into the table, resulting in a count of 0.
Raw{"answer": "0", "explanation": "The entity is removed before the flush operation, so no row is inserted into the table, resulting in a count of 0."} | верно | The unit of work schedules INSERT at flush: remove after persist cancels it. |
T15-L10 0.32 c | PostgreSQL | What does this SQL query return (PostgreSQL 17)?
```sql
CREATE TEMP TABLE t (x int);
INSERT INTO t VALUES (1), (NULL);
SELECT count(x) FROM t;
``` | «1» Пояснение: count(x) counts only non-NULL values in the column x.
Raw{"answer": 1, "explanation": "count(x) counts only non-NULL values in the column x."} | верно | count(column) skips NULLs; count(*) would return 2. |
T15-L9 0.48 c | PostgreSQL | What does this SQL query return (PostgreSQL 17)?
```sql
CREATE TEMP TABLE t (id int, x int);
INSERT INTO t VALUES (1, 10), (2, 20), (3, 30);
SELECT string_agg(s::text, ',' ORDER BY id) FROM (
SELECT id, sum(x) OVER (ORDER BY id) AS s FROM t
) q;
``` | «10,30,60» Пояснение: The window function sum(x) OVER (ORDER BY id) produces running sums 10, 30, 60, which are then concatenated by string_agg.
Raw{"answer": "10,30,60", "explanation": "The window function sum(x) OVER (ORDER BY id) produces running sums 10, 30, 60, which are then concatenated by string_agg."} | верно | With ORDER BY the default window frame is running (start to current row). |
T16-L9 0.58 c | Symfony: Messenger | What does this code output?
```php
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
use Symfony\Component\Messenger\Envelope;
final class Trace implements MiddlewareInterface
{
public function __construct(private string $tag) {}
public function handle(Envelope $e, StackInterface $stack): Envelope
{
echo $this->tag;
return $stack->next()->handle($e, $stack);
}
}
$bus = new MessageBus([new Trace('M1'), new Trace('M2')]);
$bus->dispatch(new Envelope(new stdClass()));
``` | «m1m2» Пояснение: MessageBus wraps middlewares in a stack; dispatch calls the first middleware (M1), which prints 'M1' and delegates to the next (M2), which prints 'M2' and returns the envelope.
Raw{"answer": "M1M2", "explanation": "MessageBus wraps middlewares in a stack; dispatch calls the first middleware (M1), which prints 'M1' and delegates to the next (M2), which prints 'M2' and returns the envelope."} | верно | The first-added middleware runs first (outermost). |
T16-L10 1.07 c | Symfony: Messenger | What does this code output?
```php
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\Handler\HandlerDescriptor;
use Symfony\Component\Messenger\Envelope;
class Ping {}
$n = 0;
$d1 = new HandlerDescriptor(function (Ping $m) use (&$n) { $n += 1; }, ['alias' => 'h1']);
$d2 = new HandlerDescriptor(function (Ping $m) use (&$n) { $n += 10; }, ['alias' => 'h2']);
$bus = new MessageBus([
new HandleMessageMiddleware(new HandlersLocator([Ping::class => [$d1, $d2]])),
]);
$bus->dispatch(new Envelope(new Ping()));
echo $n;
``` | «11» Пояснение: The HandleMessageMiddleware iterates through the handlers for the message class. Both $d1 and $d2 are invoked because they are both listed for Ping::class in the HandlersLocator, and HandleMessageMiddleware does not stop after the first handler by default in this simplified context (or rather, it executes all handlers in the list for the message). $n starts at 0, is incremented by 1 by the first handler, and by 10 by the second, resulting in 11.
Raw{"answer": 11, "explanation": "The HandleMessageMiddleware iterates through the handlers for the message class. Both $d1 and $d2 are invoked because they are both listed for Ping::class in the HandlersLocator, and HandleMessageMiddleware does not stop after the first handler by default in this simplified context (or rather, it executes all handlers in the list for the message). $n starts at 0, is incremented by 1 by the first handler, and by 10 by the second, resulting in 11."} | верно | All registered handlers of the message run: 1 + 10 = 11. |
T17-L9 0.31 c | PostgreSQL: transactions and indexes | What does this SQL query return (PostgreSQL 17)?
```sql
CREATE TEMP TABLE t (a int);
CREATE UNIQUE INDEX ON t (a);
INSERT INTO t VALUES (1) ON CONFLICT DO NOTHING;
INSERT INTO t VALUES (1) ON CONFLICT DO NOTHING;
SELECT count(*) FROM t;
``` | «1» Пояснение: ON CONFLICT DO NOTHING prevents duplicate insertion, so only one row exists.
Raw{"answer": 1, "explanation": "ON CONFLICT DO NOTHING prevents duplicate insertion, so only one row exists."} | верно | ON CONFLICT DO NOTHING skips the duplicate: one insert. |
T17-L10 0.56 c | PostgreSQL: transactions and indexes | What does this sequence of psql commands output?
```sql
BEGIN;
CREATE TEMP TABLE t (a int, UNIQUE (a) DEFERRABLE INITIALLY DEFERRED);
INSERT INTO t VALUES (1);
INSERT INTO t VALUES (1);
SELECT count(*) FROM t;
``` | «2» Пояснение: Because the UNIQUE constraint is defined as DEFERRABLE INITIALLY DEFERRED, the uniqueness check is postponed until the end of the transaction, allowing both rows with value 1 to be inserted successfully before any constraint violation is raised.
Raw{ ⏎ "answer": 2, ⏎ "explanation": "Because the UNIQUE constraint is defined as DEFERRABLE INITIALLY DEFERRED, the uniqueness check is postponed until the end of the transaction, allowing both rows with value 1 to be inserted successfully before any constraint violation is raised." ⏎ } | верно | DEFERRED postpones the uniqueness check to COMMIT — count sees 2 rows. |
T18-L9 2.72 c | Testing: PHPUnit | How many tests will this command run?
```php
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
final class CalcTest extends TestCase
{
public static function prov(): array
{
return [[1], [2], [3]];
}
#[DataProvider('prov')]
public function test_sum(int $x): void
{
$this->assertTrue($x > 0);
}
#[DataProvider('prov')]
public function test_sum_abs(int $x): void
{
$this->assertTrue($x > 0);
}
public function test_other(): void
{
$this->assertTrue(true);
}
}
```
Command: `phpunit CalcTest.php --filter test_sum` (PHPUnit 10.5) | «3» Пояснение: The --filter test_sum matches the method names starting with 'test_sum', specifically test_sum (which runs 3 times from the data provider) and test_sum_abs (which runs 0 times because the filter 'test_sum' is not an exact match for 'test_sum_abs' unless using regex, but standard phpunit filter is a substring or regex; wait, standard phpunit --filter uses a regex that is matched against the test name 'CalcTest::test_sum with data set #0'. So 'test_sum' matches 'test_sum' (3 tests) but does it match 'test_sum_abs'? The regex 'test_sum' matches 'test_sum_abs' because it is a substring. Let's verify. PHPUnit's filter is a regex that is matched against the fully qualified test name. 'test_sum' as a regex matches any string containing 'test_sum'. Therefore, it matches test_sum (3 cases) and test_sum_abs (3 cases). Total 6? Let's re-read carefully. Actually, in PHPUnit, the filter is a regex that is matched against the test's fully qualified name (e.g., 'CalcTest::test_sum'). If the filter is just a string, it is treated as a substring match. 'test_sum' is a substring of 'test_sum_abs'. So both methods are selected. Each has 3 data sets. So 3 + 3 = 6. However, often in these questions, if it's a simple substring, it matches both. Let's check standard behavior: `--filter test_sum` will run all tests whose name contains 'test_sum'. That includes test_sum and test_sum_abs. So 3 + 3 = 6.
Raw{"answer": 3, "explanation": "The --filter test_sum matches the method names starting with 'test_sum', specifically test_sum (which runs 3 times from the data provider) and test_sum_abs (which runs 0 times because the filter 'test_sum' is not an exact match for 'test_sum_abs' unless using regex, but standard phpunit filter is a substring or regex; wait, standard phpunit --filter uses a regex that is matched against the test name 'CalcTest::test_sum with data set #0'. So 'test_sum' matches 'test_sum' (3 tests) but does it match 'test_sum_abs'? The regex 'test_sum' matches 'test_sum_abs' because it is a substring. Let's verify. PHPUnit's filter is a regex that is matched against the fully qualified test name. 'test_sum' as a regex matches any string containing 'test_sum'. Therefore, it matches test_sum (3 cases) and test_sum_abs (3 cases). Total 6? Let's re-read carefully. Actually, in PHPUnit, the filter is a regex that is matched against the test's fully qualified name (e.g., 'CalcTest::test_sum'). If the filter is just a string, it is treated as a substring match. 'test_sum' is a substring of 'test_sum_abs'. So both methods are selected. Each has 3 data sets. So 3 + 3 = 6. However, often in these questions, if it's a simple substring, it matches both. Let's check standard behavior: `--filter test_sum` will run all tests whose name contains 'test_sum'. That includes test_sum and test_sum_abs. So 3 + 3 = 6."} | неверно верный: «6» | --filter is a substring match: test_sum also matches test_sum_abs (3+3 datasets). |
T18-L10 0.49 c | Testing: PHPUnit | How many tests will this command run, and how many of them will fail? Answer with two comma-separated numbers (ran, failed).
```php
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
final class Calc2Test extends TestCase
{
public function prov(): array
{
return [[1], [-1]];
}
#[DataProvider('prov')]
public function test_x(int $x): void
{
$this->assertTrue($x > 0);
}
}
```
Command: `phpunit Calc2Test.php` (PHPUnit 10.5) | «2, 1» Пояснение: The data provider supplies two sets of arguments ([1] and [-1]), resulting in two test runs. The assertion assertTrue($x > 0) fails for -1, so one test fails.
Raw{"answer": "2, 1", "explanation": "The data provider supplies two sets of arguments ([1] and [-1]), resulting in two test runs. The assertion assertTrue($x > 0) fails for -1, so one test fails."} | верно | A non-static provider is just a deprecation in PHPUnit 10: both datasets run and the [-1] dataset fails the assert — 2 ran, 1 failure. |
T19-L9 0.29 c | HTTP and REST API | Which HTTP method does this command send?
```bash
curl -s -d 'a=1' http://demo.local/api
``` | «post» Пояснение: The -d flag in curl automatically switches the HTTP method to POST when sending data.
Raw{"answer": "POST", "explanation": "The -d flag in curl automatically switches the HTTP method to POST when sending data."} | верно | -d/-F switches curl to POST by default. |
T19-L10 0.34 c | HTTP and REST API | Which HTTP method does this command send?
```bash
curl -s -G -d 'a=1' http://demo.local/api
``` | «get» Пояснение: The -G flag in curl specifies that the data specified with -d should be used in a GET request as a query string.
Raw{"answer": "GET", "explanation": "The -G flag in curl specifies that the data specified with -d should be used in a GET request as a query string."} | верно | -G turns -d data into the query string; the method stays GET. |
T20-L9 0.48 c | Security and OAuth | A client hits the token endpoint (RFC 6749) with a non-existent client_id. What value of the error field does the endpoint return? | «invalid_client» Пояснение: According to RFC 6749 Section 5.2, if the client authentication fails (e.g., non-existent client_id), the authorization server MUST return the 'invalid_client' error code.
Raw{"answer": "invalid_client", "explanation": "According to RFC 6749 Section 5.2, if the client authentication fails (e.g., non-existent client_id), the authorization server MUST return the 'invalid_client' error code."} | верно | Unknown client → invalid_client (RFC 6749 §5.2). |
T20-L10 0.44 c | Security and OAuth | OAuth 2.0: the client started the flow with response_type=token. In which part of the redirect_uri does the authorization server pass the access_token? | «fragment» Пояснение: In the Implicit Grant (response_type=token), the access token is returned in the fragment identifier (#) of the redirect URI to keep it out of the server logs.
Raw{"answer": "fragment", "explanation": "In the Implicit Grant (response_type=token), the access token is returned in the fragment identifier (#) of the redirect URI to keep it out of the server logs."} | верно | The implicit flow passes the token in the URL fragment (#) — it never reaches the server. |
T21-L9 3.66 c | Twig | What does this Twig template output?
```twig
{{ false|default(2) * 3 }}
``` | «6» Пояснение: In Twig, the 'default' filter only applies the default value if the value is 'null'; since 'false' is not 'null', the expression evaluates to 'false * 3'. In Twig, 'false' is cast to the integer 0, so 0 * 3 equals 0? Wait, let's re-verify Twig's type juggling. Actually, in Twig, `false` is cast to 0 when used in arithmetic. However, let's double-check the behavior of `default`. `default` uses the `??` logic or a check for `null`. If it's `null`, it replaces. `false` is not `null`. So the value is `false`. `false * 3`. In PHP/Twig context, `false` becomes 0. So 0 * 3 = 0. Let me re-read the prompt's potential trap. Is `false` considered 'empty' by `default`? No, `default` only checks for `null`. So `false` remains. `false * 3` -> `0 * 3` -> `0`.
Let's double check with a similar case. `{{ 0|default(1) }}` outputs 0. `{{ false|default(2) }}` outputs `false` (or empty string in some renderings, but in math context it's 0). Wait, if it outputs `false`, and then we multiply... Twig converts `false` to 0 for arithmetic. So 0 * 3 = 0.
Let's look at option B again. Is there any scenario where `default` catches `false`? No, that's `empty` or specific conditions. `default` is strictly `null` check.
So: `false` is passed. `false * 3`. In Twig, arithmetic operations convert boolean to integer. `false` is 0. 0 * 3 = 0.
Let's verify if Twig renders `false` as `0` or `` (empty string) first. If I do `{{ false }}`, it prints nothing. If I do `{{ false * 3 }}`, it prints `0`.
Therefore, the result is 0.
Raw{"answer": 6, "explanation": "In Twig, the 'default' filter only applies the default value if the value is 'null'; since 'false' is not 'null', the expression evaluates to 'false * 3'. In Twig, 'false' is cast to the integer 0, so 0 * 3 equals 0? Wait, let's re-verify Twig's type juggling. Actually, in Twig, `false` is cast to 0 when used in arithmetic. However, let's double-check the behavior of `default`. `default` uses the `??` logic or a check for `null`. If it's `null`, it replaces. `false` is not `null`. So the value is `false`. `false * 3`. In PHP/Twig context, `false` becomes 0. So 0 * 3 = 0. Let me re-read the prompt's potential trap. Is `false` considered 'empty' by `default`? No, `default` only checks for `null`. So `false` remains. `false * 3` -> `0 * 3` -> `0`. \n\nLet's double check with a similar case. `{{ 0|default(1) }}` outputs 0. `{{ false|default(2) }}` outputs `false` (or empty string in some renderings, but in math context it's 0). Wait, if it outputs `false`, and then we multiply... Twig converts `false` to 0 for arithmetic. So 0 * 3 = 0. \n\nLet's look at option B again. Is there any scenario where `default` catches `false`? No, that's `empty` or specific conditions. `default` is strictly `null` check. \n\nSo: `false` is passed. `false * 3`. In Twig, arithmetic operations convert boolean to integer. `false` is 0. 0 * 3 = 0. \n\nLet's verify if Twig renders `false` as `0` or `` (empty string) first. If I do `{{ false }}`, it prints nothing. If I do `{{ false * 3 }}`, it prints `0`. \n\nTherefore, the result is 0."} | верно | default replaces exactly false/null/''/[] — false becomes 2, 2*3 = 6; the naive 'default is for undefined only' yields 0. |
T21-L10 2.49 c | Twig | What exception class does render() of this template throw?
```twig
{{ 'a' ~ 1 + 2 }}
``` | «{» Пояснение: {
"answer": "0",
"explanation": "The string 'a' is coerced to the integer 0, and 1 + 2 is 3, so 0 + 3 equals 3. (Wait, the prompt asks for the exception class OR result. The expression renders without exception. The result is the string '3' because the initial operand is a string in Twig? Actually, in PHP/Twig, 'a' ~ 1 is 'a1', then 'a1' + 2 is a TypeError in PHP 8 or notice+2 in PHP 7. But usually Twig casts numeric-like strings. Let's look closer. 'a' is not numeric. In Twig, ~ is concatenation. 'a' ~ 1 becomes 'a1'. Then 'a1' + 2. In PHP, 'a1' + 2 results in a warning (PHP <8) and 0+2=2, or TypeError (PHP 8). However, standard Twig tests often rely on PHP's coercion. If it's a 'result' question, it likely expects the calculated value. Let's re-read: 'a' ~ 1 + 2. Order of operations: + is higher precedence than ~. So it is 'a' ~ (1 + 2) => 'a' ~ 3 => 'a3'. Result is string 'a3'.")
}
Raw{ ⏎ "answer": "0", ⏎ "explanation": "The string 'a' is coerced to the integer 0, and 1 + 2 is 3, so 0 + 3 equals 3. (Wait, the prompt asks for the exception class OR result. The expression renders without exception. The result is the string '3' because the initial operand is a string in Twig? Actually, in PHP/Twig, 'a' ~ 1 is 'a1', then 'a1' + 2 is a TypeError in PHP 8 or notice+2 in PHP 7. But usually Twig casts numeric-like strings. Let's look closer. 'a' is not numeric. In Twig, ~ is concatenation. 'a' ~ 1 becomes 'a1'. Then 'a1' + 2. In PHP, 'a1' + 2 results in a warning (PHP <8) and 0+2=2, or TypeError (PHP 8). However, standard Twig tests often rely on PHP's coercion. If it's a 'result' question, it likely expects the calculated value. Let's re-read: 'a' ~ 1 + 2. Order of operations: + is higher precedence than ~. So it is 'a' ~ (1 + 2) => 'a' ~ 3 => 'a3'. Result is string 'a3'.") ⏎ } | неверно верный: «runtimeerror» парсинг: текст (фолбэк) | In Twig ~ binds tighter than +: ('a' ~ 1) + 2 → string + int → a render error (RuntimeError). |
T22-L9 0.35 c | Symfony: Security and forms | What does this code output?
```php
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;
$v = Validation::createValidator();
echo count($v->validate([''], [new Assert\NotBlank()]));
``` | «1» Пояснение: The array contains an empty string, which violates the NotBlank constraint, resulting in one violation.
Raw{"answer": 1, "explanation": "The array contains an empty string, which violates the NotBlank constraint, resulting in one violation."} | неверно верный: «0» | NotBlank treats null, '', [] as blank — the array [''] is not blank. |
T22-L10 3.05 c | Symfony: Security and forms | What does this code output?
```php
use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Extension\Core\Type\TextType;
$factory = Forms::createFormFactoryBuilder()->getFormFactory();
$form = $factory->create(TextType::class);
try {
echo $form->isValid() ? 'valid' : 'invalid';
} catch (Throwable $e) {
echo get_class($e);
}
``` | «symfony\component\form\exception\invalidargumentexception» Пояснение: Creating a form using a string class name (TextType::class) without defining a name argument causes the form factory to throw an InvalidArgumentException because it cannot auto-generate a name for a non-array/string type identifier in this context (or specifically, the `create` method signature requires a name if the type is a string and not an array with a 'data_class', but more precisely, `TextType` is an abstract class or requires specific options/name generation logic that fails on strict string usage without a name). Actually, the `create` method expects `$name` as the first argument if `$type` is a string. The code calls `create(TextType::class)` omitting the name, which leads to a missing required argument or a specific exception. Wait, `create(string|object $type = null, ?string $name = null, ...)`. If `type` is a string and `name` is null, it throws `InvalidArgumentException` with the message "The form factory can only create forms from strings or arrays, but it got: TextType" or similar? No, `TextType` is a valid type string. The error is that `name` is required. Let's check Symfony docs. `createForm` signature: `createForm(string|object $type = null, string|object $name = null, ...)`. If `type` is a string, `name` is optional? No, usually name is required. If name is null, it might throw. The exception is `Symfony\Component\Form\Exception\InvalidArgumentException`.
Raw{"answer": "Symfony\\Component\\Form\\Exception\\InvalidArgumentException", "explanation": "Creating a form using a string class name (TextType::class) without defining a name argument causes the form factory to throw an InvalidArgumentException because it cannot auto-generate a name for a non-array/string type identifier in this context (or specifically, the `create` method signature requires a name if the type is a string and not an array with a 'data_class', but more precisely, `TextType` is an abstract class or requires specific options/name generation logic that fails on strict string usage without a name). Actually, the `create` method expects `$name` as the first argument if `$type` is a string. The code calls `create(TextType::class)` omitting the name, which leads to a missing required argument or a specific exception. Wait, `create(string|object $type = null, ?string $name = null, ...)`. If `type` is a string and `name` is null, it throws `InvalidArgumentException` with the message \"The form factory can only create forms from strings or arrays, but it got: TextType\" or similar? No, `TextType` is a valid type string. The error is that `name` is required. Let's check Symfony docs. `createForm` signature: `createForm(string|object $type = null, string|object $name = null, ...)`. If `type` is a string, `name` is optional? No, usually name is required. If name is null, it might throw. The exception is `Symfony\\Component\\Form\\Exception\\InvalidArgumentException`."} | неверно верный: «symfony\component\form\exception\logicexception» | isValid() on a non-submitted form throws LogicException, it does not return false. |
T23-L9 0.4 c | Symfony: configuration and services | What does this code output?
```php
use Symfony\Component\DependencyInjection\ContainerBuilder;
$c = new ContainerBuilder();
$c->register('a', stdClass::class)->setPublic(true);
$c->compile();
echo spl_object_id($c->get('a')) === spl_object_id($c->get('a')) ? 'same' : 'diff';
``` | «same» Пояснение: The Symfony DI container caches public service instances, so retrieving the same service twice returns the exact same object.
Raw{"answer": "same", "explanation": "The Symfony DI container caches public service instances, so retrieving the same service twice returns the exact same object."} | верно | Container services are shared: two get() calls yield one instance. |
T23-L10 0.46 c | Symfony: configuration and services | What does this code output?
```php
use Symfony\Component\DependencyInjection\ContainerBuilder;
$c = new ContainerBuilder();
$c->setParameter('name', 'Bob');
$c->setParameter('greeting', 'hi %name%');
$c->setParameter('message', '%greeting%!');
$c->compile();
echo $c->getParameter('message');
``` | «hi bob!» Пояснение: Symfony's ContainerBuilder resolves nested parameter placeholders recursively during compilation, replacing %name% with 'Bob' first, then using the result to resolve %greeting%.
Raw{"answer": "hi Bob!", "explanation": "Symfony's ContainerBuilder resolves nested parameter placeholders recursively during compilation, replacing %name% with 'Bob' first, then using the result to resolve %greeting%."} | верно | compile() resolves %-references transitively: %greeting% → 'hi %name%' → 'hi Bob!', the answer assembles over two hops. |
T24-L9 0.67 c | Bootstrap | What is the max-width of .container in Bootstrap 5.3 at a 992px viewport? | «940px» Пояснение: In Bootstrap 5.3, at the md breakpoint (>=768px), the .container max-width is 720px, at lg (>=992px) it's 940px, so at exactly 992px viewport, the max-width is 940px.
Raw{"answer": "940px", "explanation": "In Bootstrap 5.3, at the md breakpoint (>=768px), the .container max-width is 720px, at lg (>=992px) it's 940px, so at exactly 992px viewport, the max-width is 940px."} | неверно верный: «960» | 5.x container widths: 540/720/960/1140/1320 (sm–xxl); 992 → 960px. |
T24-L10 4.42 c | Bootstrap | Which utility sets the text color in Bootstrap 5.3 for `<p class="text-danger text-primary">…</p>`? Answer with the winning class name. | «text-primary» Пояснение: In CSS, when multiple utility classes with the same specificity are applied, the one defined later in the stylesheet takes precedence. In Bootstrap's source and compiled CSS, .text-primary appears before .text-danger? Actually, checking Bootstrap's docs and CSS order: text utilities are generated in a specific order. However, a simpler way to think about it is that both classes have the same specificity. If we look at the actual Bootstrap 5.3 CSS, the .text-colors are defined in the _utilities.scss or via Sass maps. Usually, they are output in the order of the map. But often, if you have conflicting text colors, the last one in the class attribute does NOT automatically win; it depends on the order in the CSS file. Let's check the Bootstrap docs or common behavior. Actually, a common trick is that if they are from the same utility, the last one in the CSS file wins. In Bootstrap 5, the text utilities are ordered by their name or specific internal order. However, looking at the specific classes: text-danger and text-primary. If we inspect the CSS, .text-primary is typically defined before .text-danger? Or is it the other way? Let's look at the standard order: text-*, then bg-*. Within text-*, they are often sorted alphabetically or by type. If alphabetical: black, body, white, then custom (primary, secondary, etc.)? No, usually primary, secondary, success, info, warning, danger, light, dark. If that's the order, .text-danger comes AFTER .text-primary. Therefore, .text-danger would win. Wait, let me double check. If the order is primary, secondary, success, info, warning, danger, then danger is later in the file, so danger wins. But the question asks which utility sets the text color for that specific snippet. If danger wins, the answer is text-danger. If primary wins, the answer is text-primary. Let's re-evaluate standard Bootstrap CSS output order. In _variables.scss or _utilities.scss, the $text-utilities map is used. The order in the map determines the CSS order. In Bootstrap 5, the map is: $theme-colors which is (primary: ..., secondary: ..., success: ..., info: ..., warning: ..., danger: ..., light: ..., dark: ...). So .text-danger is generated AFTER .text-primary. Therefore, .text-danger has higher precedence because it appears later in the CSS. So the color is danger. The class name is text-danger.
Raw{"answer": "text-primary", "explanation": "In CSS, when multiple utility classes with the same specificity are applied, the one defined later in the stylesheet takes precedence. In Bootstrap's source and compiled CSS, .text-primary appears before .text-danger? Actually, checking Bootstrap's docs and CSS order: text utilities are generated in a specific order. However, a simpler way to think about it is that both classes have the same specificity. If we look at the actual Bootstrap 5.3 CSS, the .text-colors are defined in the _utilities.scss or via Sass maps. Usually, they are output in the order of the map. But often, if you have conflicting text colors, the last one in the class attribute does NOT automatically win; it depends on the order in the CSS file. Let's check the Bootstrap docs or common behavior. Actually, a common trick is that if they are from the same utility, the last one in the CSS file wins. In Bootstrap 5, the text utilities are ordered by their name or specific internal order. However, looking at the specific classes: text-danger and text-primary. If we inspect the CSS, .text-primary is typically defined before .text-danger? Or is it the other way? Let's look at the standard order: text-*, then bg-*. Within text-*, they are often sorted alphabetically or by type. If alphabetical: black, body, white, then custom (primary, secondary, etc.)? No, usually primary, secondary, success, info, warning, danger, light, dark. If that's the order, .text-danger comes AFTER .text-primary. Therefore, .text-danger would win. Wait, let me double check. If the order is primary, secondary, success, info, warning, danger, then danger is later in the file, so danger wins. But the question asks which utility sets the text color for that specific snippet. If danger wins, the answer is text-danger. If primary wins, the answer is text-primary. Let's re-evaluate standard Bootstrap CSS output order. In _variables.scss or _utilities.scss, the $text-utilities map is used. The order in the map determines the CSS order. In Bootstrap 5, the map is: $theme-colors which is (primary: ..., secondary: ..., success: ..., info: ..., warning: ..., danger: ..., light: ..., dark: ...). So .text-danger is generated AFTER .text-primary. Therefore, .text-danger has higher precedence because it appears later in the CSS. So the color is danger. The class name is text-danger."} | неверно верный: «text-danger» | Specificity ties — the later rule wins: text-danger is declared after text-primary. |
T25-L9 0.45 c | Clean architecture | Layers: Domain, Application, Infrastructure. Deptrac rules: Application → Domain; Infrastructure → Domain, Application; Domain → Domain only.
How many violations will deptrac report for this class?
```php
namespace App\Domain;
use App\Application\PlaceOrder;
use App\Infrastructure\Db;
class OrderService
{
public function __construct(
private PlaceOrder $handler,
private Db $db,
) {}
}
``` | «2» Пояснение: The class is in Domain, which can only depend on Domain; it violates this by depending on both Application (PlaceOrder) and Infrastructure (Db).
Raw{"answer": "2", "explanation": "The class is in Domain, which can only depend on Domain; it violates this by depending on both Application (PlaceOrder) and Infrastructure (Db)."} | верно | Domain may depend only on Domain: PlaceOrder (Application) + Db (Infrastructure) = 2. |
T25-L10 0.58 c | Clean architecture | Layers: Domain, Application, Infrastructure. Deptrac rules: Application → Domain; Infrastructure → Domain, Application; Domain → Domain only.
How many violations will deptrac report for this class?
```php
namespace App\Domain;
use App\Application\PlaceOrder;
use App\Infrastructure\Db;
class BillingService
{
public function __construct(
private PlaceOrder $handler,
private Db $db,
private \App\Infrastructure\Logger $logger,
) {}
}
``` | «3» Пояснение: The Domain layer can only depend on itself, but this class in App\Domain uses three classes from other layers (App\Application\PlaceOrder, App\Infrastructure\Db, App\Infrastructure\Logger), resulting in 3 dependency violations.
Raw```json ⏎ {"answer": 3, "explanation": "The Domain layer can only depend on itself, but this class in App\\Domain uses three classes from other layers (App\\Application\\PlaceOrder, App\\Infrastructure\\Db, App\\Infrastructure\\Logger), resulting in 3 dependency violations."} ⏎ ``` | верно | The inline FQCN \App\Infrastructure\Logger counts too: Application + Db + Logger = 3. |
T26-L10 0.44 c | DDD | What does this code output?
```php
final class Money
{
public function __construct(public readonly int $amount) {}
public function add(Money $o): Money
{
return new self($this->amount + $o->amount);
}
}
$a = new Money(10);
$c = $a->add(new Money(5));
echo $a->amount . ',' . $c->amount;
``` | «10,15» Пояснение: The method creates a new Money instance with the sum, so $a remains unchanged at 10 and $c is 15.
Raw```json ⏎ {"answer": "10,15", "explanation": "The method creates a new Money instance with the sum, so $a remains unchanged at 10 and $c is 15."} ⏎ ``` | верно | The VO is immutable: add() returns a new instance; the original is unchanged. |
T26-L9 0.38 c | DDD | What does this code output?
```php
final class Order
{
private array $items = [];
public function add(string $sku): void
{
$this->items[$sku] = true;
}
public function count(): int
{
return count($this->items);
}
public function remove(string $sku): void
{
if (count($this->items) === 1) {
throw new DomainException('last item');
}
unset($this->items[$sku]);
}
}
$o = new Order;
$o->add('a');
try {
$o->remove('a');
} catch (DomainException) {
}
echo $o->count();
``` | «1» Пояснение: The exception is thrown before the item is removed, so the item remains in the array.
Raw```json ⏎ { ⏎ "answer": 1, ⏎ "explanation": "The exception is thrown before the item is removed, so the item remains in the array." ⏎ } ⏎ ``` | верно | The failed remove leaves aggregate state unchanged: the invariant threw before unset — count stays 1. |
VC-L9 3.36 c | PHP 8.4–8.5 | What does this code output on PHP 8.5?
```php
class C
{
public function hi(): string { return 'hi'; }
}
echo new C()->hi();
``` | «hi» Пояснение: The code creates an instance of class C and calls its hi() method, which returns the string 'hi'.
Raw{"answer": "hi", "explanation": "The code creates an instance of class C and calls its hi() method, which returns the string 'hi'."} | верно | Since 8.4, new in a method chain works without wrapping parentheses. |
VC-L10 3.38 c | PHP 8.4–8.5 | What does this code output on PHP 8.5?
```php
class Heavy
{
public int $v = 0;
}
$r = new ReflectionClass(Heavy::class);
$o = $r->newLazyGhost(function (Heavy $obj) {
$obj->v = 21;
});
echo $r->isUninitializedLazyObject($o) ? 'yes' : 'no';
$o->v;
echo $r->isUninitializedLazyObject($o) ? 'yes' : 'no';
``` | «yesno» Пояснение: The code first checks if the lazy object is uninitialized, prints 'yes', then accesses $o->v which triggers the callback and initialization, and finally checks if it is still uninitialized, printing 'no'.
Raw{"answer": "yesno", "explanation": "The code first checks if the lazy object is uninitialized, prints 'yes', then accesses $o->v which triggers the callback and initialization, and finally checks if it is still uninitialized, printing 'no'."} | верно | newLazyGhost (8.4): the object stays lazy until first access — reading a property initializes it and clears the flag. |
T28-L9 0.42 c | Symfony: versions | The project was upgraded from Symfony 6.4 to 8.1. What does this code output on 8.1?
```php
echo class_exists(\Symfony\Component\Security\Guard\AbstractGuardAuthenticator::class)
? 'yes' : 'no';
``` | «no» Пояснение: The Symfony Guard component and AbstractGuardAuthenticator class were deprecated in Symfony 5.3, removed in 6.0, so they do not exist in Symfony 8.1.
Raw{"answer": "no", "explanation": "The Symfony Guard component and AbstractGuardAuthenticator class were deprecated in Symfony 5.3, removed in 6.0, so they do not exist in Symfony 8.1."} | верно | Guard authentication was removed in Symfony 7.0 — the class is gone in 8.1. |
T28-L10 0.4 c | Symfony: versions | The project was upgraded from Symfony 6.4 to 8.1. What does this code output on 8.1?
```php
echo class_exists(\Symfony\Component\Routing\Loader\AnnotationClassLoader::class)
? 'yes' : 'no';
echo class_exists(\Symfony\Component\Routing\Loader\AttributeClassLoader::class)
? 'yes' : 'no';
``` | «noyes» Пояснение: In Symfony 7+, AnnotationClassLoader was removed (deprecated in 6.4, removed in 7.0) and replaced by AttributeClassLoader, which exists in 8.1.
Raw{"answer": "noyes", "explanation": "In Symfony 7+, AnnotationClassLoader was removed (deprecated in 6.4, removed in 7.0) and replaced by AttributeClassLoader, which exists in 8.1."} | верно | Annotation loaders were removed in 7.0; only attribute loaders remain (Annotation→Attribute). |