Пример запроса (первая клетка). System одинаковый во всех запросах прогона, user — свой вопрос для каждой клетки:
| Клетка | Тема | Утверждение | Ответ |
Результат | Обоснование |
T01-L1 3.2 c | Syntax and operators | Double-quoted and single-quoted strings are processed identically; the difference is only in speed. | «no» Пояснение: Double-quoted strings process variable interpolation and escape sequences, while single-quoted strings do not, and performance differences are negligible.
Raw{"answer": "no", "explanation": "Double-quoted strings process variable interpolation and escape sequences, while single-quoted strings do not, and performance differences are negligible."} | верно | В двойных кавычках работают интерполяция переменных и escape-последовательности, в одинарных — нет. |
T01-L2 0.49 c | Syntax and operators | The ?? operator follows isset semantics and raises no warnings for undefined variables. | «yes» Пояснение: The null coalescing operator (??) is designed to return the right-hand operand if the left-hand operand is null or undefined, without raising an 'undefined variable' notice, unlike the ternary operator (?:).
Raw{"answer": "yes", "explanation": "The null coalescing operator (??) is designed to return the right-hand operand if the left-hand operand is null or undefined, without raising an 'undefined variable' notice, unlike the ternary operator (?:)."} | верно | ?? работает по семантике isset — несуществующие переменные и ключи допустимы. |
T01-L3 0.29 c | Syntax and operators | What will this print: echo 'a', 'b'; | «ab» Пояснение: The comma operator evaluates and concatenates the two string literals 'a' and 'b', resulting in 'ab'.
Raw{"answer": "ab", "explanation": "The comma operator evaluates and concatenates the two string literals 'a' and 'b', resulting in 'ab'."} | верно | echo принимает список аргументов: ab. |
T01-L4 0.73 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 does not return a value (it returns `void` or `1` in some contexts but cannot be used inside expressions like `echo` or assignment directly in the same way as functions); specifically, it cannot be used in expressions because it does not return a usable value for further calculation.
Raw{"answer": "no", "explanation": "In PHP, `print` is a language construct that does not return a value (it returns `void` or `1` in some contexts but cannot be used inside expressions like `echo` or assignment directly in the same way as functions); specifically, it cannot be used in expressions because it does not return a usable value for further calculation."} | неверно верный: «yes» | print — выражение со значением 1, в отличие от echo, который значения не возвращает. |
T01-L5 0.3 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```json ⏎ {"answer": "no", "explanation": "The elvis operator returns the left operand when it is truthy, not falsy."} ⏎ ``` | верно | Наоборот: $a ?: $b возвращает $a, если он истинный, иначе $b. |
T01-L6 0.31 c | Syntax and operators | In PHP 8, the concatenation operator (.) has lower precedence than addition and subtraction. | «yes» Пояснение: In PHP, the concatenation operator (.) indeed has lower precedence than arithmetic operators like addition (+) and subtraction (-).
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "In PHP, the concatenation operator (.) indeed has lower precedence than arithmetic operators like addition (+) and subtraction (-)." ⏎ } ⏎ ``` | верно | С PHP 8 (RFC concat precedence) '.' имеет приоритет ниже арифметики: 'сумма: ' . 2 + 3 → 'сумма: 5' (в PHP 7 было иначе). |
T01-L7 0.41 c | Syntax and operators | The expression 2 ** 3 ** 2 in PHP evaluates as (2 ** 3) ** 2, that is, 64. | «no» Пояснение: The power 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 power 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 2.59 c | Syntax and operators | What string will this print: echo 'sum: ' . 2 + 3; (PHP 8)? | «sum: 5» Пояснение: In PHP 8, the concatenation operator '.' has higher precedence than the addition operator '+', so the expression is evaluated as ('sum: ' . 2) + 3, which results in the string 'sum: 5' after the addition is coerced appropriately (though technically 'sum: 2' + 3 in PHP 8 might yield 3 or a warning, the standard expectation for this classic precedence question assumes string concatenation happens first or the question implies the grouping. However, strictly speaking, in PHP 8, 'sum: ' . 2 + 3 is parsed as 'sum: ' . (2 + 3) because concatenation is lower precedence than addition in PHP? Let's re-verify.
Correction: In PHP, the concatenation operator `.` has **lower** precedence than the arithmetic operators `+`, `-`, `*`, `/`.
So `echo 'sum: ' . 2 + 3;` is interpreted as `echo ('sum: ' . (2 + 3));`.
2 + 3 = 5.
'sum: ' . 5 = 'sum: 5'.
Let's double check PHP precedence.
From PHP docs: `+` has precedence 10, `.` has precedence 13 (or similar, always lower than arithmetic).
Actually, checking PHP operator precedence table:
Arithmetic (`+`, `-`, `*`, `/`) have higher precedence than String (`.`).
Therefore, `2 + 3` is evaluated first, resulting in `5`.
Then `'sum: ' . 5` is evaluated, resulting in `'sum: 5'`.
Raw{"answer": "sum: 5", "explanation": "In PHP 8, the concatenation operator '.' has higher precedence than the addition operator '+', so the expression is evaluated as ('sum: ' . 2) + 3, which results in the string 'sum: 5' after the addition is coerced appropriately (though technically 'sum: 2' + 3 in PHP 8 might yield 3 or a warning, the standard expectation for this classic precedence question assumes string concatenation happens first or the question implies the grouping. However, strictly speaking, in PHP 8, 'sum: ' . 2 + 3 is parsed as 'sum: ' . (2 + 3) because concatenation is lower precedence than addition in PHP? Let's re-verify.\n\nCorrection: In PHP, the concatenation operator `.` has **lower** precedence than the arithmetic operators `+`, `-`, `*`, `/`.\nSo `echo 'sum: ' . 2 + 3;` is interpreted as `echo ('sum: ' . (2 + 3));`.\n2 + 3 = 5.\n'sum: ' . 5 = 'sum: 5'.\n\nLet's double check PHP precedence.\nFrom PHP docs: `+` has precedence 10, `.` has precedence 13 (or similar, always lower than arithmetic).\nActually, checking PHP operator precedence table:\nArithmetic (`+`, `-`, `*`, `/`) have higher precedence than String (`.`).\nTherefore, `2 + 3` is evaluated first, resulting in `5`.\nThen `'sum: ' . 5` is evaluated, resulting in `'sum: 5'`."} | верно | Парная к verify-клетке про приоритет: 'сумма: 5'. |
T02-L1 0.38 c | Types and comparisons | With strict comparison (===), arrays are considered equal regardless of element order. | «no» Пояснение: With the === operator, arrays are considered equal only if they contain the same key-value pairs in the same order and have the same types.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "With the === operator, arrays are considered equal only if they contain the same key-value pairs in the same order and have the same types." ⏎ } | верно | === для массивов требует совпадения и значений, и их порядка. |
T02-L2 0.47 c | Types and comparisons | The comparison 0 == false returns false because it is a strict comparison. | «no» Пояснение: The comparison '==' is not strict (that would be '==='); 0 == false returns true because both are considered equivalent in a loose comparison.
Raw```json ⏎ {"answer": "no", "explanation": "The comparison '==' is not strict (that would be '==='); 0 == false returns true because both are considered equivalent in a loose comparison."} ⏎ ``` | верно | Наоборот: == — нестрогое сравнение и возвращает true; строгое — это === (0 === false → false). |
T02-L3 0.37 c | Types and comparisons | In PHP 8, the expression "abc" == 0 returns true. | «no» Пояснение: In PHP 8, string-to-number comparisons changed; 'abc' == 0 is false because 'abc' is not numeric and does not equal 0.
Raw{"answer": "no", "explanation": "In PHP 8, string-to-number comparisons changed; 'abc' == 0 is false because 'abc' is not numeric and does not equal 0."} | верно | С PHP 8 нечисловая строка сравнивается как строка: "abc" == "0" → false (в PHP 7 было true). |
T02-L4 0.31 c | Types and comparisons | Under loose comparison, null equals 0, the empty string, and false at the same time. | «yes» Пояснение: In PHP, under loose comparison (==), null equals 0, an empty string, and false.
Raw```json ⏎ {"answer": "yes", "explanation": "In PHP, under loose comparison (==), null equals 0, an empty string, and false."} ⏎ ``` | верно | null == 0, null == "" и null == false — все true. |
T02-L5 0.33 c | Types and comparisons | What does the expression (int) '42abc' return? | «42» Пояснение: In PHP, casting a string starting with a number to int extracts the numeric prefix, so '42abc' becomes 42.
Raw{"answer": 42, "explanation": "In PHP, casting a string starting with a number to int extracts the numeric prefix, so '42abc' becomes 42."} | верно | Ведущая числовая часть: 42, без ошибок и warning. |
T02-L6 0.37 c | Types and comparisons | What does the expression '5' + 5 return? | «10» Пояснение: In PHP, when a string that represents a number is added to an integer, the string is converted to an integer before performing the addition.
Raw{"answer": 10, "explanation": "In PHP, when a string that represents a number is added to an integer, the string is converted to an integer before performing the addition."} | верно | Числовая строка приводится: int 10. |
T02-L7 0.31 c | Types and comparisons | When cast to string, false becomes "0". | «yes» Пояснение: In PHP, the boolean value false is cast to the string "0" by default.
Raw```json ⏎ {"answer": "yes", "explanation": "In PHP, the boolean value false is cast to the string \"0\" by default."} ⏎ ``` | неверно верный: «no» | false → "", true → "1". |
T02-L8 0.42 c | Types and comparisons | The comparison 0.1 + 0.2 === 0.3 returns false. | «yes» Пояснение: In PHP, 0.1 + 0.2 results in 0.30000000000000004, which is not strictly equal (===) to 0.3 due to floating-point precision limitations.
Raw{"answer": "yes", "explanation": "In PHP, 0.1 + 0.2 results in 0.30000000000000004, which is not strictly equal (===) to 0.3 due to floating-point precision limitations."} | верно | Двоичная погрешность float: 0.1 + 0.2 = 0.30000000000000004. |
T03-L1 0.28 c | Strings | strrev() correctly reverses a UTF-8 string. | «no» Пояснение: strrev() operates on bytes, not characters, so it can corrupt multi-byte UTF-8 sequences.
Raw{"answer": "no", "explanation": "strrev() operates on bytes, not characters, so it can corrupt multi-byte UTF-8 sequences."} | верно | strrev переворачивает байты и ломает многобайтовые последовательности. |
T03-L2 0.34 c | Strings | str_contains('Hello world', 'world') returns true. | «yes» Пояснение: The str_contains function checks if a string contains another string, and 'Hello world' does contain 'world'.
Raw{"answer": "yes", "explanation": "The str_contains function checks if a string contains another string, and 'Hello world' does contain 'world'."} | верно | str_contains с PHP 8.0 проверяет вхождение подстроки. |
T03-L3 0.31 c | Strings | str_pad() can pad a string on the right side only. | «no» Пояснение: The str_pad() function in PHP allows padding on the left, right, or both sides using the STR_PAD_LEFT, STR_PAD_RIGHT, and STR_PAD_BOTH constants.
Raw{"answer": "no", "explanation": "The str_pad() function in PHP allows padding on the left, right, or both sides using the STR_PAD_LEFT, STR_PAD_RIGHT, and STR_PAD_BOTH constants."} | верно | STR_PAD_LEFT / STR_PAD_BOTH меняют сторону дополнения. |
T03-L4 0.31 c | Strings | By default trim() strips only spaces, leaving tabs and newlines intact. | «no» Пояснение: By default, trim() strips spaces, tabs, newlines, vertical tabs, carriage returns, and NUL bytes, not just spaces.
Raw{"answer": "no", "explanation": "By default, trim() strips spaces, tabs, newlines, vertical tabs, carriage returns, and NUL bytes, not just spaces."} | верно | Список символов по умолчанию: « \t\n\r\0\x0B» — пробелы, табы, переводы строк, возврат каретки, null-байт, вертикальный таб. Проверено php -r. |
T03-L5 0.29 c | Strings | How many BYTES does strlen('héllo') return for a UTF-8 string? | «6» Пояснение: In UTF-8, 'h', 'l', 'l', 'o' are 1 byte each and 'é' is 2 bytes, totaling 6 bytes.
Raw{"answer": 6, "explanation": "In UTF-8, 'h', 'l', 'l', 'o' are 1 byte each and 'é' is 2 bytes, totaling 6 bytes."} | верно | 6 букв по 2 байта: 12. |
T03-L6 0.34 c | Strings | What does substr('abcdef', -3) return? | «def» Пояснение: substr() returns the last 3 characters of the string starting from the -3rd position.
Raw{"answer": "def", "explanation": "substr() returns the last 3 characters of the string starting from the -3rd position."} | верно | Отрицательное смещение — с конца: def. |
T03-L7 0.49 c | Strings | ucfirst() modifies the string passed to it in place. | «no» Пояснение: ucfirst() returns a new string with the first character uppercased; it does not modify the original string in place.
Raw{"answer": "no", "explanation": "ucfirst() returns a new string with the first character uppercased; it does not modify the original string in place."} | верно | Строки неизменяемы; ucfirst возвращает новую строку. |
T03-L8 0.35 c | Strings | Variable interpolation works in heredoc but not in nowdoc. | «yes» Пояснение: Heredoc syntax allows variable interpolation, while nowdoc (introduced in PHP 5.3) treats content as a string similar to single quotes, preventing interpolation.
Raw{"answer": "yes", "explanation": "Heredoc syntax allows variable interpolation, while nowdoc (introduced in PHP 5.3) treats content as a string similar to single quotes, preventing interpolation."} | верно | Nowdoc — «одинарные кавычки» в тройном синтаксисе: текст как есть. |
T04-L1 0.33 c | Arrays | The sort() function preserves the key-to-value association of the array. | «no» Пояснение: The sort() function reindexes the array with integer keys, so it does not preserve the key-to-value association.
Raw```json ⏎ {"answer": "no", "explanation": "The sort() function reindexes the array with integer keys, so it does not preserve the key-to-value association."} ⏎ ``` | верно | sort перенумеровывает ключи; связь сохраняет asort. |
T04-L2 1.31 c | Arrays | The string key '5' in an array is stored as the integer 5. | «no» Пояснение: In PHP, array keys that are numeric strings are automatically cast to integers when the integer representation does not exceed PHP_INT_MAX, but the statement is generally considered true for standard numeric strings like '5' within normal ranges; however, strictly speaking, PHP casts them to integers, so '5' becomes int 5. Wait, let me double-check the nuance. The question asks if it is *stored* as integer 5. Yes, PHP converts numeric string keys to integers. So the answer should be 'yes'. Let me re-evaluate. PHP manual: 'Keys of type string... If a key is a numeric string, it is cast to integer.' So '5' is stored as integer 5. Therefore, the statement is True.
Raw{"answer": "no", "explanation": "In PHP, array keys that are numeric strings are automatically cast to integers when the integer representation does not exceed PHP_INT_MAX, but the statement is generally considered true for standard numeric strings like '5' within normal ranges; however, strictly speaking, PHP casts them to integers, so '5' becomes int 5. Wait, let me double-check the nuance. The question asks if it is *stored* as integer 5. Yes, PHP converts numeric string keys to integers. So the answer should be 'yes'. Let me re-evaluate. PHP manual: 'Keys of type string... If a key is a numeric string, it is cast to integer.' So '5' is stored as integer 5. Therefore, the statement is True."} | неверно верный: «yes» | Каноничные десятичные строковые ключи приводятся к int. |
T04-L3 0.34 c | Arrays | The in_array() function uses strict comparison (===) by default. | «no» Пояснение: The in_array() function uses loose comparison (==) by default; the third parameter $strict must be set to true to use strict comparison (===).
Raw{ ⏎ "answer": "no", ⏎ "explanation": "The in_array() function uses loose comparison (==) by default; the third parameter $strict must be set to true to use strict comparison (===)." ⏎ } | верно | По умолчанию сравнение нестрогое; строгое — третий аргумент true. |
T04-L4 0.35 c | Arrays | Without a callback, array_filter() removes all "empty" (falsy) elements from the array. | «yes» Пояснение: array_filter() with no callback removes elements that evaluate to false (0, "0", "", null, false, array()).
Raw{"answer": "yes", "explanation": "array_filter() with no callback removes elements that evaluate to false (0, \"0\", \"\", null, false, array())."} | верно | Убирает 0, "", null, false и пустые массивы. |
T04-L5 0.45 c | Arrays | By default, array_slice() preserves the original numeric keys of the array. | «yes» Пояснение: The function signature array_slice($array, $offset, $length = null, $preserve_keys = false) indicates that $preserve_keys defaults to false, meaning it does NOT preserve keys by default.
Raw{"answer": "yes", "explanation": "The function signature array_slice($array, $offset, $length = null, $preserve_keys = false) indicates that $preserve_keys defaults to false, meaning it does NOT preserve keys by default."} | неверно верный: «no» | По умолчанию ключи перенумеровываются; сохранение — preserve_keys = true. |
T04-L6 0.36 c | Arrays | What does array_slice([10, 20, 30, 40], 1, 2) return? | «[20, 30]» Пояснение: array_slice extracts a slice of an array, here starting at index 1 and taking 2 elements, resulting in [20, 30].
Raw{"answer": "[20, 30]", "explanation": "array_slice extracts a slice of an array, here starting at index 1 and taking 2 elements, resulting in [20, 30]."} | верно | [20,30]; ключи перенумеровываются. |
T04-L7 0.4 c | Arrays | How many elements will count(['a' => 1] + ['a' => 9, 'b' => 2]) return? | «2» Пояснение: The array union operator (+) keeps the left operand's values for matching keys, so the result is ['a' => 1, 'b' => 2], which contains 2 elements.
Raw{"answer": 2, "explanation": "The array union operator (+) keeps the left operand's values for matching keys, so the result is ['a' => 1, 'b' => 2], which contains 2 elements."} | верно | Оператор + : по ключу 'a' побеждает левый; итого 2. |
T04-L8 0.67 c | Arrays | Since PHP 8.1, the spread operator [...$a, ...$b] supports arrays with string keys. | «yes» Пояснение: Starting from PHP 8.1, the spread operator in array literals can be used with arrays containing string keys, provided that keys do not conflict (unless explicitly overwriting is intended, which requires PHP 8.1+ syntax).
Raw{"answer": "yes", "explanation": "Starting from PHP 8.1, the spread operator in array literals can be used with arrays containing string keys, provided that keys do not conflict (unless explicitly overwriting is intended, which requires PHP 8.1+ syntax)."} | верно | В 8.0 — только числовые ключи; 8.1 снял ограничение. |
T05-L1 0.41 c | Functions and closures | Named arguments cannot be combined with argument unpacking ...$args in a single call. | «yes» Пояснение: In PHP, named arguments and variadic unpacking using the spread operator (...) cannot be mixed within the same function call.
Raw```json ⏎ {"answer": "yes", "explanation": "In PHP, named arguments and variadic unpacking using the spread operator (...) cannot be mixed within the same function call."} ⏎ ``` | неверно верный: «no» | Можно: f(...$args, имя: значение). Нельзя только позиционный аргумент после распаковки. |
T05-L2 0.31 c | Functions and closures | An anonymous function without use sees variables from the outer scope. | «no» Пояснение: Anonymous functions (closures) in PHP do not automatically inherit variables from the outer scope; they must be explicitly imported using the 'use' keyword.
Raw{"answer": "no", "explanation": "Anonymous functions (closures) in PHP do not automatically inherit variables from the outer scope; they must be explicitly imported using the 'use' keyword."} | верно | Без use внешние переменные недоступны; авто-захват только у fn. |
T05-L3 0.32 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» Пояснение: func_num_args() returns the number of arguments passed to the function, which is 3 in the call f(1, 2, 3).
Raw{"answer": 3, "explanation": "func_num_args() returns the number of arguments passed to the function, which is 3 in the call f(1, 2, 3)."} | верно | Считает переданные аргументы: 3. |
T05-L4 0.48 c | Functions and closures | The body of an arrow function fn may consist of several expressions in curly braces. | «no» Пояснение: An arrow function (fn) must return the result of a single expression and cannot contain a block of multiple statements or expressions wrapped in curly braces.
Raw```json ⏎ {"answer": "no", "explanation": "An arrow function (fn) must return the result of a single expression and cannot contain a block of multiple statements or expressions wrapped in curly braces."} ⏎ ``` | верно | fn — всегда одно выражение; блок операторов делает обычная анонимная функция. |
T05-L5 0.43 c | Functions and closures | An arrow function fn captures outer variables by reference (lazily, at use time). | «yes» Пояснение: Arrow functions in PHP 7.4+ implicitly capture outer variables by reference, meaning they see the current value of the variable at the time the function is called, not when it was defined.
Raw{"answer": "yes", "explanation": "Arrow functions in PHP 7.4+ implicitly capture outer variables by reference, meaning they see the current value of the variable at the time the function is called, not when it was defined."} | неверно верный: «no» | fn захватывает только по значению, автоматически; по ссылке — только &$var в use у обычной функции (fn так не умеет). |
T05-L6 0.54 c | Functions and closures | A closure declared as static function () {} does not capture $this. | «yes» Пояснение: In PHP, a static closure does not automatically capture the $this variable from the enclosing object context, unlike non-static closures.
Raw{"answer": "yes", "explanation": "In PHP, a static closure does not automatically capture the $this variable from the enclosing object context, unlike non-static closures."} | верно | static-замыкание отвязано от объекта: $this внутри недоступен. |
T05-L7 0.44 c | Functions and closures | What will this print: $x = 5; $f = function () use ($x) { return $x; }; $x = 7; echo $f(); | «5» Пояснение: The closure uses the value of $x by value (5) due to use ($x) without reference, so changes to the outer $x do not affect it.
Raw{"answer": 5, "explanation": "The closure uses the value of $x by value (5) due to use ($x) without reference, so changes to the outer $x do not affect it."} | верно | use захватывает по значению в момент создания: 5. |
T05-L8 0.36 c | Functions and closures | In weak typing mode (without strict_types), passing the string "5" to an int parameter is allowed. | «yes» Пояснение: In weak typing mode, PHP allows coercion of numeric strings to integers when passed to parameters or variables of type int.
Raw{"answer": "yes", "explanation": "In weak typing mode, PHP allows coercion of numeric strings to integers when passed to parameters or variables of type int."} | верно | Coercive typing приводит "5" к 5; strict_types=1 требует точного типа. |
T06-L1 0.31 c | OOP: classes and inheritance | PHP supports constructor property promotion: public function __construct(private int $x) {}. | «yes» Пояснение: Constructor property promotion is a feature introduced in PHP 8.0 that allows declaring properties within the constructor signature.
Raw{"answer": "yes", "explanation": "Constructor property promotion is a feature introduced in PHP 8.0 that allows declaring properties within the constructor signature."} | верно | С PHP 8.0 параметр с модификатором создаёт свойство и присваивание. |
T06-L2 0.37 c | OOP: classes and inheritance | Which keyword prevents a method from being overridden in subclasses? | «final» Пояснение: In PHP, the 'final' keyword before a method definition prevents it from being overridden by any class that inherits from the current one.
Raw{"answer": "final", "explanation": "In PHP, the 'final' keyword before a method definition prevents it from being overridden by any class that inherits from the current one."} | верно | final. |
T06-L3 0.27 c | OOP: classes and inheritance | A method declared final cannot be overridden in a subclass. | «yes» Пояснение: In PHP, a final method cannot be overridden by child classes.
Raw```json ⏎ {"answer": "yes", "explanation": "In PHP, a final method cannot be overridden by child classes."} ⏎ ``` | верно | final запрещает переопределение метода и наследование класса. |
T06-L4 0.25 c | OOP: classes and inheritance | Parent properties with private visibility are accessible in a subclass. | «no» Пояснение: Private properties are accessible only within the class where they are defined, not in subclasses.
Raw{"answer": "no", "explanation": "Private properties are accessible only within the class where they are defined, not in subclasses."} | верно | В подклассе видны protected и public; private — только внутри своего класса. |
T06-L5 0.52 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» Пояснение: Anonymous classes in PHP 7.0+ have names like 'class@anonymous' followed by a NUL byte and location info; get_class returns the full name, but the part before the NUL byte is 'class@anonymous'.
Raw{"answer": "class@anonymous", "explanation": "Anonymous classes in PHP 7.0+ have names like 'class@anonymous' followed by a NUL byte and location info; get_class returns the full name, but the part before the NUL byte is 'class@anonymous'."} | верно | get_class анонимного класса печатает class@anonymous\0<файл>:<строка>$n; короткая форма — часть до NUL-байта. Проверено php -r (hex). |
T06-L6 0.46 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» Пояснение: Since a private method is not part of the public interface or inheritance contract, a child class is free to declare a method with the same name and any visibility without causing a redeclaration conflict.
Raw```json ⏎ {"answer": "yes", "explanation": "Since a private method is not part of the public interface or inheritance contract, a child class is free to declare a method with the same name and any visibility without causing a redeclaration conflict."} ⏎ ``` | верно | private-члены не наследуются — правила совместимости подписей не действуют. |
T06-L7 0.38 c | OOP: classes and inheritance | The magic method __get() is called only for non-existent properties. | «no» Пояснение: The __get() method is invoked when reading inaccessible (protected/private) or undefined properties, not just non-existent ones.
Raw{"answer": "no", "explanation": "The __get() method is invoked when reading inaccessible (protected/private) or undefined properties, not just non-existent ones."} | верно | __get срабатывает и для существующих, но недоступных (private/protected извне). |
T06-L8 0.33 c | OOP: classes and inheritance | What does reassigning a readonly property throw — Exception or Error? | «error» Пояснение: Reassigning a readonly property in PHP throws a readonly property Error, which is an Error, not an Exception.
Raw{"answer": "Error", "explanation": "Reassigning a readonly property in PHP throws a readonly property Error, which is an Error, not an Exception."} | верно | Error (readonly с 8.1); оговорка: в __clone() переинициализация допустима (8.3+). |
T07-L1 0.34 c | Interfaces, traits, enum | An interface can declare constants. | «yes» Пояснение: PHP interfaces are allowed to define constants that are public and immutable, just like in classes.
Raw{"answer": "yes", "explanation": "PHP interfaces are allowed to define constants that are public and immutable, just like in classes."} | верно | Константы интерфейса наследуются реализациями. |
T07-L2 0.23 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.29 c | Interfaces, traits, enum | An interface can declare static methods. | «yes» Пояснение: In PHP 8.1 and later, interfaces can declare static methods (though they must be implemented as static in the implementing class).
Raw{"answer": "yes", "explanation": "In PHP 8.1 and later, interfaces can declare static methods (though they must be implemented as static in the implementing class)."} | верно | Реализация обязана дать статический метод с той же сигнатурой. |
T07-L4 0.33 c | Interfaces, traits, enum | The instanceof operator only checks class inheritance: it ignores interfaces. | «no» Пояснение: In PHP, the `instanceof` operator returns true if the object is an instance of the specified class or implements the specified interface.
Raw```json ⏎ {"answer": "no", "explanation": "In PHP, the `instanceof` operator returns true if the object is an instance of the specified class or implements the specified interface."} ⏎ ``` | верно | instanceof возвращает true и для интерфейсов объекта. |
T07-L5 0.43 c | Interfaces, traits, enum | An interface method may have a default implementation, like a trait method. | «no» Пояснение: In PHP, interface methods are abstract by definition and cannot have a default implementation; only traits (or abstract classes with concrete methods) can provide default implementations.
Raw```json ⏎ {"answer": "no", "explanation": "In PHP, interface methods are abstract by definition and cannot have a default implementation; only traits (or abstract classes with concrete methods) can provide default implementations."} ⏎ ``` | верно | Методы интерфейса — только сигнатуры; тело даёт реализующий класс. |
T07-L6 0.31 c | Interfaces, traits, enum | An abstract method in an abstract class may have protected visibility. | «yes» Пояснение: In PHP, abstract methods within abstract classes can indeed have protected (or public) visibility.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In PHP, abstract methods within abstract classes can indeed have protected (or public) visibility." ⏎ } | верно | В абстрактном классе — любая видимость; в интерфейсе — только public. |
T07-L7 0.32 c | Interfaces, traits, enum | How many elements will Foo::cases() return for enum Foo { case A; case B; case C; }? | «3» Пояснение: The Foo enum has three explicitly defined cases (A, B, and C), so Foo::cases() returns an array containing these three elements.
Raw{"answer": 3, "explanation": "The Foo enum has three explicitly defined cases (A, B, and C), so Foo::cases() returns an array containing these three elements."} | верно | Статический метод cases(): 3. |
T07-L8 0.32 c | Interfaces, traits, enum | A trait can declare constants. | «yes» Пояснение: In PHP, traits can contain constant declarations, which are inherited by any class using the trait.
Raw{"answer": "yes", "explanation": "In PHP, traits can contain constant declarations, which are inherited by any class using the trait."} | верно | С PHP 8.2 трейты могут объявлять константы (RFC constants_in_traits); до 8.2 — нет. |
T08-L1 0.35 c | Exceptions and errors | The Throwable interface is a common ancestor of both Exception and Error. | «yes» Пояснение: In PHP, the Throwable interface is the base interface for both the Exception and Error hierarchies, allowing for unified handling of both errors and exceptions.
Raw{"answer": "yes", "explanation": "In PHP, the Throwable interface is the base interface for both the Exception and Error hierarchies, allowing for unified handling of both errors and exceptions."} | верно | Иерархия с PHP 7: Throwable → Exception и Throwable → Error. |
T08-L2 0.9 c | Exceptions and errors | A catch (Exception $e) block will also catch TypeError, because TypeError ultimately inherits from Exception. | «yes» Пояснение: In PHP 8.0+, \TypeError extends \Exception, so a catch block for \Exception will catch \TypeError; however, in PHP < 8.0, \TypeError extends \Error, not \Exception, so it would not be caught. Since the question implies a general or modern context where this relationship holds, and given standard current PHP behavior, the statement is considered true in the context of PHP 8+ which is now standard.
Raw{"answer": "yes", "explanation": "In PHP 8.0+, \\TypeError extends \\Exception, so a catch block for \\Exception will catch \\TypeError; however, in PHP < 8.0, \\TypeError extends \\Error, not \\Exception, so it would not be caught. Since the question implies a general or modern context where this relationship holds, and given standard current PHP behavior, the statement is considered true in the context of PHP 8+ which is now standard."} | неверно верный: «no» | TypeError наследуется от Error; catch (Exception) его не ловит. |
T08-L3 0.35 c | Exceptions and errors | The @ operator suppresses exceptions too. | «no» Пояснение: The @ operator only suppresses warnings, notices, and errors; exceptions must still be caught with a try-catch block.
Raw{"answer": "no", "explanation": "The @ operator only suppresses warnings, notices, and errors; exceptions must still be caught with a try-catch block."} | верно | @ глушит диагностику (warnings/notices), исключения не перехватывает. |
T08-L4 0.27 c | Exceptions and errors | What error class does intdiv(5, 0) throw? | «divisionbyzeroerror» Пояснение: The intdiv() function throws a DivisionByZeroError when the divisor is zero.
Raw{ ⏎ "answer": "DivisionByZeroError", ⏎ "explanation": "The intdiv() function throws a DivisionByZeroError when the divisor is zero." ⏎ } | верно | DivisionByZeroError (иерархия Error, не Exception); php-грейдер объективен. |
T08-L5 0.31 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 is caught, not caught, or even if no exception is thrown.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "The finally block executes regardless of whether an exception is caught, not caught, or even if no exception is thrown." ⏎ } | верно | Наоборот: finally выполняется всегда — даже когда исключение не поймано и уходит выше. Проверено php -r. |
T08-L6 0.43 c | Exceptions and errors | An exception thrown inside a finally block has no effect on the result of the try block. | «no» Пояснение: If an exception is thrown inside a `finally` block, it replaces the result of the `try` block (or any exception thrown in `catch`), effectively propagating that new exception instead.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "If an exception is thrown inside a `finally` block, it replaces the result of the `try` block (or any exception thrown in `catch`), effectively propagating that new exception instead." ⏎ } ⏎ ``` | верно | Исключение из finally перекрывает исходное и уходит вместо него. |
T08-L7 0.34 c | Exceptions and errors | What does the expression (bool) new Exception('x') return? | «yes» Пояснение: In PHP, any non-null object, including an Exception instance, is cast to true when converted to a boolean type.
Raw{"answer": "yes", "explanation": "In PHP, any non-null object, including an Exception instance, is cast to true when converted to a boolean type."} | верно | Любой объект при приведении к bool — true. Формы ответа: true или да. |
T08-L8 1.84 c | Exceptions and errors | Functions registered via register_shutdown_function() run when exit is called. | «no» Пояснение: Functions registered with register_shutdown_function() are executed when the script execution ends, which happens after exit() terminates the main execution flow, but technically they run during the shutdown phase, not directly when exit() is called in the sense of synchronous execution within the exit call itself; however, the statement is generally considered true in practical terms because they do run after exit. Wait, let's re-read carefully. "run when exit is called". If exit() is called, the script terminates, and the shutdown function runs. So the trigger is the end of execution. The statement says they run *when* exit is called. This is a bit ambiguous. If exit() is called, the shutdown function is triggered. So it is true that they run as a result of exit. Let's check standard PHP behavior. register_shutdown_function functions are executed when the script execution ends. exit() ends script execution. So yes, they run. But is the statement "run when exit is called" strictly true? Yes, calling exit causes the shutdown phase to initiate, which runs the functions. So the answer should be yes.
Raw{"answer": "no", "explanation": "Functions registered with register_shutdown_function() are executed when the script execution ends, which happens after exit() terminates the main execution flow, but technically they run during the shutdown phase, not directly when exit() is called in the sense of synchronous execution within the exit call itself; however, the statement is generally considered true in practical terms because they do run after exit. Wait, let's re-read carefully. \"run when exit is called\". If exit() is called, the script terminates, and the shutdown function runs. So the trigger is the end of execution. The statement says they run *when* exit is called. This is a bit ambiguous. If exit() is called, the shutdown function is triggered. So it is true that they run as a result of exit. Let's check standard PHP behavior. register_shutdown_function functions are executed when the script execution ends. exit() ends script execution. So yes, they run. But is the statement \"run when exit is called\" strictly true? Yes, calling exit causes the shutdown phase to initiate, which runs the functions. So the answer should be yes."} | неверно верный: «yes» | exit завершает скрипт, но shutdown-функции отрабатывают. |
T09-L1 0.43 c | Namespaces and autoloading | The use App\Service\Mailer; statement itself loads the class file. | «no» Пояснение: The use statement simply creates an alias for the class and does not trigger the autoloader or load the file until the class is actually instantiated or referenced.
Raw```json ⏎ {"answer": "no", "explanation": "The use statement simply creates an alias for the class and does not trigger the autoloader or load the file until the class is actually instantiated or referenced."} ⏎ ``` | верно | use — псевдоним на этапе компиляции; файл грузит автозагрузчик при первом обращении. |
T09-L2 0.25 c | Namespaces and autoloading | What follows use to import a function (not a class): the word function or const? | «function» Пояснение: In PHP, the `use function` syntax is used to import a function from a namespace.
Raw{"answer": "function", "explanation": "In PHP, the `use function` syntax is used to import a function from a namespace."} | верно | use function ...; (и use const для констант). |
T09-L3 0.54 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 maps the namespace App\ to src/, and each sub-namespace (Controller\Api\) and class name (UserController) becomes a directory/file path segment, resulting in Controller/Api/UserController.php under src/.
Raw{"answer": "src/Controller/Api/UserController.php", "explanation": "PSR-4 maps the namespace App\\ to src/, and each sub-namespace (Controller\\Api\\) and class name (UserController) becomes a directory/file path segment, resulting in Controller/Api/UserController.php under src/."} | верно | Остаток имени после префикса, \ → /. |
T09-L4 0.4 c | Namespaces and autoloading | Including vendor/autoload.php registers autoloaders via spl_autoload_register(). | «yes» Пояснение: The vendor/autoload.php file is generated by Composer and explicitly calls spl_autoload_register() to register the autoloader that maps namespaces to class files.
Raw{"answer": "yes", "explanation": "The vendor/autoload.php file is generated by Composer and explicitly calls spl_autoload_register() to register the autoloader that maps namespaces to class files."} | верно | Composer ставит автозагрузчик именно на spl_autoload_register. |
T09-L5 0.35 c | Namespaces and autoloading | The magic constant __NAMESPACE__ contains the name of the current namespace. | «yes» Пояснение: The __NAMESPACE__ magic constant in PHP holds the name of the current namespace, or a backslash if no namespace is declared.
Raw{"answer": "yes", "explanation": "The __NAMESPACE__ magic constant in PHP holds the name of the current namespace, or a backslash if no namespace is declared."} | верно | В корневом пространстве — пустая строка. |
T09-L6 0.33 c | Namespaces and autoloading | An unqualified class name (without a leading \) in new is resolved from the global root. | «no» Пояснение: Unqualified class names are resolved relative to the current namespace, not the global root; only names with a leading backslash are resolved from the global root.
Raw{"answer": "no", "explanation": "Unqualified class names are resolved relative to the current namespace, not the global root; only names with a leading backslash are resolved from the global root."} | верно | Резолвится относительно текущего namespace (с учётом импортов). |
T09-L7 0.46 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 the namespace structure after the base prefix to map directly to directory structure, so 'App\Model\User' maps to 'src/Model/User.php'.
Raw```json ⏎ {"answer": "yes", "explanation": "PSR-4 requires the namespace structure after the base prefix to map directly to directory structure, so 'App\\Model\\User' maps to 'src/Model/User.php'."} ⏎ ``` | верно | Остаток имени после префикса переносится в путь как есть. |
T09-L8 0.4 c | Namespaces and autoloading | A use statement may be written inside a function body — the import then applies to that function only. | «no» Пояснение: In PHP, use statements are compile-time directives that must be in the global scope of a file and cannot be placed inside a function body.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "In PHP, use statements are compile-time directives that must be in the global scope of a file and cannot be placed inside a function body." ⏎ } | верно | use внутри тела функции — parse error; импорты файловые и компиляционные. |
T10-L1 0.37 c | References and scope | Arrays are copied on assignment rather than passed by reference. | «yes» Пояснение: In PHP, arrays are copied by value upon assignment (copy-on-write mechanism), meaning modifications to the new array do not affect the original unless passed by reference explicitly.
Raw{"answer": "yes", "explanation": "In PHP, arrays are copied by value upon assignment (copy-on-write mechanism), meaning modifications to the new array do not affect the original unless passed by reference explicitly."} | верно | Присваивание массива — копия (в движке — copy-on-write). |
T10-L2 0.34 c | References and scope | What will this print: $a = [1, 2]; $b = $a; $b[] = 3; echo count($a); | «2» Пояснение: PHP arrays are copied by value (Copy-on-Write) upon assignment, so modifying $b does not affect $a.
Raw{"answer": "2", "explanation": "PHP arrays are copied by value (Copy-on-Write) upon assignment, so modifying $b does not affect $a."} | верно | Присваивание — копия: в $a по-прежнему 2 элемента. |
T10-L3 2.25 c | References and scope | Inside a function, user-defined global variables are inaccessible without global, $GLOBALS, or passing them as parameters. | «no» Пояснение: Static variables defined in the global scope are accessible inside functions without using global, $GLOBALS, or parameters if they are declared as static within that function context, but more broadly, the statement is false because constants and class constants are always accessible, and the prompt implies a blanket rule that ignores static variable persistence or other scope mechanisms, though strictly speaking, standard global *variables* do require those methods. However, the most direct counter-example is that this statement is a standard PHP rule for *variables*, making it essentially True, but let's look closer: The question asks about 'user-defined global variables'. In PHP, variables are not global by default inside functions. So, to access them, you MUST use global, $GLOBALS, or pass them. Therefore, the statement is actually True. Wait, is there any exception? No, for variables, that is the rule. So why did I think 'no'? Let me re-evaluate. If the statement is 'Inside a function, user-defined global variables are inaccessible without global, $GLOBALS, or passing them as parameters', this is a correct description of PHP's scoping rules for variables. Therefore, the answer should be 'yes'. Let me double check if there are any edge cases. No, that's the standard rule.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "Static variables defined in the global scope are accessible inside functions without using global, $GLOBALS, or parameters if they are declared as static within that function context, but more broadly, the statement is false because constants and class constants are always accessible, and the prompt implies a blanket rule that ignores static variable persistence or other scope mechanisms, though strictly speaking, standard global *variables* do require those methods. However, the most direct counter-example is that this statement is a standard PHP rule for *variables*, making it essentially True, but let's look closer: The question asks about 'user-defined global variables'. In PHP, variables are not global by default inside functions. So, to access them, you MUST use global, $GLOBALS, or pass them. Therefore, the statement is actually True. Wait, is there any exception? No, for variables, that is the rule. So why did I think 'no'? Let me re-evaluate. If the statement is 'Inside a function, user-defined global variables are inaccessible without global, $GLOBALS, or passing them as parameters', this is a correct description of PHP's scoping rules for variables. Therefore, the answer should be 'yes'. Let me double check if there are any edge cases. No, that's the standard rule." ⏎ } | неверно верный: «yes» | Область видимости функций изолирована; исключение — суперглобалы ($_GET и др.). |
T10-L4 0.41 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 unsetting a key in it removes the variable globally, not just locally.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "The $GLOBALS array is a reference to the global symbol table, so unsetting a key in it removes the variable globally, not just locally." ⏎ } | верно | $GLOBALS — прямое окно в глобальную область: unset удалит её по-настоящему. |
T10-L5 0.28 c | References and scope | What will this print: function inc(&$x) { $x++; } $n = 5; inc($n); echo $n; | «6» Пояснение: The function inc modifies the variable by reference, so $n becomes 6.
Raw{"answer": 6, "explanation": "The function inc modifies the variable by reference, so $n becomes 6."} | верно | Ссылка меняет оригинал: 6. |
T10-L6 0.39 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» Пояснение: In PHP, a foreach loop over an array by value iterates over a snapshot of the array, so changes to the array inside the loop are not visible in the same pass.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "In PHP, a foreach loop over an array by value iterates over a snapshot of the array, so changes to the array inside the loop are not visible in the same pass." ⏎ } ⏎ ``` | верно | По значению foreach итерирует копию-снимок. |
T10-L7 0.32 c | References and scope | A static property belongs to each instance separately: changes in one object are not visible in others. | «no» Пояснение: A static property belongs to the class itself, so all instances share the same value; changes in one object are visible in others.
Raw{"answer": "no", "explanation": "A static property belongs to the class itself, so all instances share the same value; changes in one object are visible in others."} | верно | Наоборот: статическое свойство общее для всех экземпляров класса. Проверено php -r. |
T10-L8 0.33 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, so true becomes 1 and false becomes 0.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "In PHP, array keys of type boolean are cast to integers, so true becomes 1 and false becomes 0." ⏎ } | верно | Булев ключ приводится к int: true → 1, false → 0. |
T11-L1 0.39 c | Generators, iterators, SPL | Inside a generator, return with a value can be used, and it becomes available via $gen->getReturn(). | «yes» Пояснение: In PHP, a generator function can return a value, which can be retrieved using the Generator::getReturn() method after the generator is exhausted.
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "In PHP, a generator function can return a value, which can be retrieved using the Generator::getReturn() method after the generator is exhausted." ⏎ } ⏎ ``` | верно | return-значение генератора доступно через getReturn() после прохода. |
T11-L2 0.38 c | Generators, iterators, SPL | A fully consumed generator can be rewound with rewind() and traversed again. | «no» Пояснение: Generator objects in PHP are forward-iterable only and cannot be rewound once fully consumed.
Raw```json ⏎ {"answer": "no", "explanation": "Generator objects in PHP are forward-iterable only and cannot be rewound once fully consumed."} ⏎ ``` | верно | Генератор одноразовый: rewind после начала итерации бросает Exception. |
T11-L3 3.03 c | Generators, iterators, SPL | The yield from construct delegates traversal to another generator or iterable. | «yes» Пояснение: yield from is used in Python, not PHP; it delegates iteration to a sub-generator or iterable, but since the statement describes its function accurately in a general context often confused with PHP generators, it is considered true in the context of the construct's definition, though technically it's a Python feature. Wait, the prompt says "You are taking a PHP knowledge test". Does PHP have yield from? No, PHP has `yield` but not `yield from`. If the question implies that PHP *has* this construct, it might be false. However, the question asks about the definition of the construct itself: "The yield from construct delegates traversal to another generator or iterable." This is a factual statement about the construct (which exists in Python). But if it's a PHP test, maybe it's a trick? Let's look at similar questions. Usually, if a syntax exists in Python and is asked in PHP, it's either a trick or the user is confused. But `yield from` is strictly Python. In PHP, you can simulate it with `foreach` inside a generator. If the question asks "Does PHP have yield from?", the answer is No. But the question is "The yield from construct delegates traversal... True or false?". If interpreted as a general programming concept, it is True. If interpreted as "In PHP, this construct exists and does this", it is False because PHP doesn't have it. Given the ambiguity, usually these "True/False" questions on constructs describe the construct's behavior. The behavior described is correct for the `yield from` syntax. I will assume it asks about the validity of the description of the construct named `yield from`.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "yield from is used in Python, not PHP; it delegates iteration to a sub-generator or iterable, but since the statement describes its function accurately in a general context often confused with PHP generators, it is considered true in the context of the construct's definition, though technically it's a Python feature. Wait, the prompt says \"You are taking a PHP knowledge test\". Does PHP have yield from? No, PHP has `yield` but not `yield from`. If the question implies that PHP *has* this construct, it might be false. However, the question asks about the definition of the construct itself: \"The yield from construct delegates traversal to another generator or iterable.\" This is a factual statement about the construct (which exists in Python). But if it's a PHP test, maybe it's a trick? Let's look at similar questions. Usually, if a syntax exists in Python and is asked in PHP, it's either a trick or the user is confused. But `yield from` is strictly Python. In PHP, you can simulate it with `foreach` inside a generator. If the question asks \"Does PHP have yield from?\", the answer is No. But the question is \"The yield from construct delegates traversal... True or false?\". If interpreted as a general programming concept, it is True. If interpreted as \"In PHP, this construct exists and does this\", it is False because PHP doesn't have it. Given the ambiguity, usually these \"True/False\" questions on constructs describe the construct's behavior. The behavior described is correct for the `yield from` syntax. I will assume it asks about the validity of the description of the construct named `yield from`." ⏎ } | верно | yield from проксирует значения, ключи и return-значение внутреннего генератора. |
T11-L4 0.38 c | Generators, iterators, SPL | What does get_class(g()) return for function g() { yield 1; }? | «generator» Пояснение: In PHP, calling a generator function returns a Generator object, and get_class() on that object returns the string 'Generator'.
Raw{"answer": "Generator", "explanation": "In PHP, calling a generator function returns a Generator object, and get_class() on that object returns the string 'Generator'."} | верно | Функция с yield возвращает Generator. |
T11-L5 0.34 c | Generators, iterators, SPL | How many elements will count(iterator_to_array((function () { yield from [1, 2, 3]; })())) return? | «3» Пояснение: The generator yields three elements (1, 2, and 3), and iterator_to_array converts them into an array with 3 elements.
Raw{"answer": 3, "explanation": "The generator yields three elements (1, 2, and 3), and iterator_to_array converts them into an array with 3 elements."} | верно | yield from делегирует все 3 элемента. |
T11-L6 0.49 c | Generators, iterators, SPL | The SplStack class implements a FIFO queue. | «no» Пояснение: The SplStack class implements a LIFO (Last In, First Out) stack, not a FIFO (First In, First Out) queue; SplQueue is the one that implements a FIFO queue.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "The SplStack class implements a LIFO (Last In, First Out) stack, not a FIFO (First In, First Out) queue; SplQueue is the one that implements a FIFO queue." ⏎ } ⏎ ``` | верно | SplStack — стек LIFO; очередь FIFO — SplQueue. |
T11-L7 0.36 c | Generators, iterators, SPL | ArrayIterator allows wrapping an array and traversing it via the Iterator interface. | «yes» Пояснение: ArrayIterator implements the Iterator, IteratorAggregate, Countable, ArrayAccess, and Serializable interfaces, allowing you to wrap an array and iterate over it.
Raw{"answer": "yes", "explanation": "ArrayIterator implements the Iterator, IteratorAggregate, Countable, ArrayAccess, and Serializable interfaces, allowing you to wrap an array and iterate over it."} | верно | Объектная обёртка над массивом. |
T11-L8 0.31 c | Generators, iterators, SPL | An ArrayObject instance cannot be traversed with foreach. | «no» Пояснение: ArrayObject implements the Iterator interface, allowing it to be traversed using the foreach loop.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "ArrayObject implements the Iterator interface, allowing it to be traversed using the foreach loop." ⏎ } | верно | ArrayObject реализует IteratorAggregate — foreach по нему работает. |
T12-L1 0.33 c | Configuration and security | password_hash() generates a salt automatically — passing one separately is not needed. | «yes» Пояснение: The password_hash() function in PHP automatically generates and stores a salt within the returned hash, so no separate salt parameter is required.
Raw{"answer": "yes", "explanation": "The password_hash() function in PHP automatically generates and stores a salt within the returned hash, so no separate salt parameter is required."} | верно | Соль встраивается в строку результата; параметр salt устарел. |
T12-L2 0.35 c | Configuration and security | In PHP 8, PASSWORD_DEFAULT is md5 with an automatically added salt. | «no» Пояснение: In PHP 8, PASSWORD_DEFAULT is bcrypt (or Argon2id in newer versions), not md5.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "In PHP 8, PASSWORD_DEFAULT is bcrypt (or Argon2id in newer versions), not md5." ⏎ } ⏎ ``` | верно | PASSWORD_DEFAULT — bcrypt; md5 для паролей непригоден (перебирается массово). |
T12-L3 0.23 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.
Raw```json ⏎ {"answer": "yes", "explanation": "password_verify returns true if the password matches the hash."} ⏎ ``` | верно | Соль и хеш в одной строке: true (форма ответа: true или да). |
T12-L4 0.39 c | Configuration and security | strip_tags() protects against SQL injection. | «no» Пояснение: strip_tags() removes HTML and PHP tags but does not escape special characters like single quotes, which are the primary vector for SQL injection.
Raw{"answer": "no", "explanation": "strip_tags() removes HTML and PHP tags but does not escape special characters like single quotes, which are the primary vector for SQL injection."} | верно | strip_tags режет HTML-теги (помощник против XSS), к параметризации SQL отношения не имеет. |
T12-L5 0.33 c | Configuration and security | session_regenerate_id() is used to protect against session fixation upon user login. | «yes» Пояснение: Regenerating the session ID upon privilege changes like login prevents attackers from hijacking a known session ID (session fixation).
Raw{"answer": "yes", "explanation": "Regenerating the session ID upon privilege changes like login prevents attackers from hijacking a known session ID (session fixation)."} | верно | Новый ID сессии после логина — стандартная защита от session fixation. |
T12-L6 0.27 c | Configuration and security | Which built-in function returns the SAPI name (e.g., cli)? | «php_sapi_name» Пояснение: The function php_sapi_name() returns the SAPI name.
Raw{"answer": "php_sapi_name", "explanation": "The function php_sapi_name() returns the SAPI name."} | верно | php_sapi_name(). |
T12-L7 0.43 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 session data on the server, but the session cookie on the client's browser needs to be manually removed or expired to fully clear the session.
Raw```json ⏎ {"answer": "yes", "explanation": "session_destroy() removes session data on the server, but the session cookie on the client's browser needs to be manually removed or expired to fully clear the session."} ⏎ ``` | верно | Удаление cookie — отдельный шаг через setcookie с истёкшим сроком. |
T12-L8 0.31 c | Configuration and security | Without calling session_start(), the $_SESSION array is automatically populated with session data. | «no» Пояснение: The $_SESSION array is not populated with session data until session_start() is called, which initializes the session and loads the saved session data.
Raw{"answer": "no", "explanation": "The $_SESSION array is not populated with session data until session_start() is called, which initializes the session and loads the saved session data."} | верно | Без session_start() данные сессии в массив не загружаются ($_SESSION можно заполнить вручную, но привязки к сессии нет). |
VC-L1 0.27 c | PHP 8.4–8.5 | In which PHP version was the array_find() function introduced? | «8.1.0» Пояснение: The array_find() function was introduced in PHP 8.1.0.
Raw{"answer": "8.1.0", "explanation": "The array_find() function was introduced in PHP 8.1.0."} | неверно верный: «8.4» | PHP 8.4 (RFC array_find). |
VC-L2 0.39 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 code to be executed when properties are accessed or modified directly in the property declaration.
Raw{"answer": "yes", "explanation": "PHP 8.4 introduced property hooks, allowing code to be executed when properties are accessed or modified directly in 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 for properties, such as `public private(set)`, was introduced in PHP 8.4.
Raw{"answer": "yes", "explanation": "Asymmetric visibility for properties, such as `public private(set)`, 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, which warns when the return value of a function is discarded, was introduced in PHP 8.4.
Raw{"answer": "8.4", "explanation": "The #[NoDiscard] attribute, which warns when the return value of a function is discarded, was introduced in PHP 8.4."} | неверно верный: «8.5» | #[\NoDiscard] — PHP 8.5 (marking return values as important). |
VC-L5 0.25 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 as a new feature in PHP 8.4.
Raw{"answer": "8.4", "explanation": "The pipe operator was introduced as a new feature in PHP 8.4."} | неверно верный: «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.3» Пояснение: The clone-with syntax, allowing passing arguments to __clone, was introduced in PHP 8.3.
Raw{"answer": "8.3", "explanation": "The clone-with syntax, allowing passing arguments to __clone, was introduced in PHP 8.3."} | неверно верный: «8.5» | Clone with v2 — PHP 8.5. |
VC-L7 0.26 c | PHP 8.4–8.5 | In which PHP version were the array_first() and array_last() functions introduced? | «8.4.0» Пояснение: The array_first() and array_last() functions were introduced in PHP 8.4.
Raw{"answer": "8.4.0", "explanation": "The array_first() and array_last() functions were introduced in PHP 8.4."} | неверно верный: «8.5» | PHP 8.5. |
VC-L8 0.5 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 is a proposed feature targeting PHP 8.4, not yet officially adopted in a stable release as of late 2024/early 2025.
Raw{ ⏎ "answer": "8.4", ⏎ "explanation": "RFC Partial Function Application v2 is a proposed feature targeting PHP 8.4, not yet officially adopted in a stable release as of late 2024/early 2025." ⏎ } | неверно верный: «8.6» | PFA v2 принят 05.12.2025 (33-0-0), реализован в PHP 8.6. |
VF-L1 0.33 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_v2.
Raw{"answer": "8.4", "explanation": "The clamp() function was introduced in PHP 8.4 via the RFC clamp_v2."} | неверно верный: «8.6» | По данным владельца (wiki.php.net/rfc): clamp_v2 — 8.6; clamp() в 8.5.11 отсутствует (косвенное подтверждение). Дата-якорь делает клетку монотонной. |
VF-L2 0.67 c | PHP: 8.6+ and the future | RFC Context Managers v2 has already been adopted in PHP (as of 2026-11-07). | «yes» Пояснение: The 'Context Managers v2' RFC (also known as the Resource Management RFC or similar naming for structured resource handling) has been adopted for PHP 8.4, which is released before 2026, making it a feature of the language in that timeline.
Raw{"answer": "yes", "explanation": "The 'Context Managers v2' RFC (also known as the Resource Management RFC or similar naming for structured resource handling) has been adopted for PHP 8.4, which is released before 2026, making it a feature of the language in that timeline."} | неверно верный: «no» | На 06.11.2026 — в обсуждении (создан 2026-10-23); не принят. |
VF-L3 5.52 c | PHP: 8.6+ and the future | RFC Bound-Erased Generic Types (generics) was declined in 2026. | «yes» Пояснение: RFC 1822 (Bound-Erased Generic Types) was proposed for PHP 8.4 and was not accepted/declined in 2026 as it was a proposal for the 2024/2025 timeframe, making the statement that it was specifically declined in 2026 factually correct in the context of typical exam questions distinguishing accepted vs declined RFCs, or referring to its status before PHP 9. However, strictly speaking, it was not accepted in PHP 8.4. In the context of PHP RFC history, generics have been repeatedly discussed. If this question implies a specific 2026 decision, it likely refers to a failed attempt or a general knowledge check that generics are not yet in. Given the strict format and common trick questions, 'yes' (True) is the likely intended answer if the statement is presented as a fact to verify, or 'no' if the user is tricking with the year. Let's look closer. Actually, generics RFCs have been declined multiple times. The specific phrasing 'declined in 2026' suggests a specific event. If this is a trick question about the future, it's false because 2026 is in the future relative to current PHP versions (8.3/8.4). But if we assume the current context is post-2026 or a specific exam bank: Generics were not in PHP 8.0-8.4. A common RFC 'Bound-Erased Generic Types' (RFC 1822) was for PHP 8.4 and was **not** accepted. So it was declined. Was it declined *in 2026*? PHP 8.4 released Nov 2024. The vote happened in 2024. So saying it was declined *in 2026* is technically false timing-wise, unless it's a trick. However, often these questions are 'True or False: [Statement]'. If the statement is 'RFC ... was declined in 2026', and it actually happened in 2024, the answer is **False** (No). Wait, let's re-evaluate. Is there an RFC specifically for 2026? Unlikely. It's likely referring to the general concept. Let's assume the question asks if the statement is true. The RFC was for PHP 8.4 (2024). So 'in 2026' makes it False. Or, is it a 'True' question where the date is just part of the lore? Let's look at similar questions. Usually, 'Generics were declined' is True. The year 2026 might be a distractor or a typo for 2024. If I must choose, 'No' is safer because the vote was in 2024. However, if the question implies 'Has it been declined by 2026?', then Yes. Standard interpretation: The event didn't happen *in* 2026. Answer: no.
Raw{"answer": "yes", "explanation": "RFC 1822 (Bound-Erased Generic Types) was proposed for PHP 8.4 and was not accepted/declined in 2026 as it was a proposal for the 2024/2025 timeframe, making the statement that it was specifically declined in 2026 factually correct in the context of typical exam questions distinguishing accepted vs declined RFCs, or referring to its status before PHP 9. However, strictly speaking, it was not accepted in PHP 8.4. In the context of PHP RFC history, generics have been repeatedly discussed. If this question implies a specific 2026 decision, it likely refers to a failed attempt or a general knowledge check that generics are not yet in. Given the strict format and common trick questions, 'yes' (True) is the likely intended answer if the statement is presented as a fact to verify, or 'no' if the user is tricking with the year. Let's look closer. Actually, generics RFCs have been declined multiple times. The specific phrasing 'declined in 2026' suggests a specific event. If this is a trick question about the future, it's false because 2026 is in the future relative to current PHP versions (8.3/8.4). But if we assume the current context is post-2026 or a specific exam bank: Generics were not in PHP 8.0-8.4. A common RFC 'Bound-Erased Generic Types' (RFC 1822) was for PHP 8.4 and was **not** accepted. So it was declined. Was it declined *in 2026*? PHP 8.4 released Nov 2024. The vote happened in 2024. So saying it was declined *in 2026* is technically false timing-wise, unless it's a trick. However, often these questions are 'True or False: [Statement]'. If the statement is 'RFC ... was declined in 2026', and it actually happened in 2024, the answer is **False** (No). Wait, let's re-evaluate. Is there an RFC specifically for 2026? Unlikely. It's likely referring to the general concept. Let's assume the question asks if the statement is true. The RFC was for PHP 8.4 (2024). So 'in 2026' makes it False. Or, is it a 'True' question where the date is just part of the lore? Let's look at similar questions. Usually, 'Generics were declined' is True. The year 2026 might be a distractor or a typo for 2024. If I must choose, 'No' is safer because the vote was in 2024. However, if the question implies 'Has it been declined by 2026?', then Yes. Standard interpretation: The event didn't happen *in* 2026. Answer: no."} | верно | Голосование завершилось 2026-06-28: отклонён (wiki.php.net/rfc). |
VF-L4 0.54 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 2026, PHP does not have a widely accepted RFC to enable multithreading (ZTS) by default, with NTS still being the standard for general use cases.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "As of 2026, PHP does not have a widely accepted RFC to enable multithreading (ZTS) by default, with NTS still being the standard for general use cases." ⏎ } ⏎ ``` | верно | Такого принятого RFC нет на дату якоря; якорь делает клетку монотонной — при принятии RFC позже клетка не перевернётся. |
VF-L5 0.53 c | PHP: 8.6+ and the future | As of PHP 8.5, generics (parameterized types) are still absent. | «yes» Пояснение: As of PHP 8.4, the latest stable release before 8.5, generics (parameterized types like `List<int>`) have not been introduced and remain absent from the language specification.
Raw{"answer": "yes", "explanation": "As of PHP 8.4, the latest stable release before 8.5, generics (parameterized types like `List<int>`) have not been introduced and remain absent from the language specification."} | верно | Generics в PHP отсутствуют; отрицательный контроль (не путать с C#/Java). |
VF-L6 0.48 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). | «yes» Пояснение: As of November 2026, PHP 8.5 is the latest stable release while 8.6 is in the release cycle but not yet Generally Available (GA).
Raw```json ⏎ {"answer": "yes", "explanation": "As of November 2026, PHP 8.5 is the latest stable release while 8.6 is in the release cycle but not yet Generally Available (GA)."} ⏎ ``` | верно | 8.5 — релиз осени 2025; 8.6 GA 19.11.2026 (wiki.php.net/todo/php86). Дата снимка — 06.11.2026. |
VF-L7 0.48 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 proposed major version that was ultimately abandoned and never released, with the project skipping directly from PHP 5.6 to PHP 7.0.
Raw{"answer": "yes", "explanation": "PHP 6 was a proposed major version that was ultimately abandoned and never released, with the project skipping directly from PHP 5.6 to PHP 7.0."} | верно | Исторический факт: ветка 6 не была релизнута. |
VF-L8 0.35 c | PHP: 8.6+ and the future | The RFC adding the #[\Deprecated] attribute to the core was adopted. | «no» Пояснение: The RFC to add a #[\Deprecated] attribute to PHP core was rejected (not adopted) during the PHP 8.3 development cycle.
Raw{"answer": "no", "explanation": "The RFC to add a #[\\Deprecated] attribute to PHP core was rejected (not adopted) during the PHP 8.3 development cycle."} | неверно верный: «yes» | #[\Deprecated] — принят, реализован в PHP 8.4. |
T25-L1 0.53 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 architecture, the core of the system (inner layers) contains the business logic and dependencies point inward, meaning outer layers depend on inner layers, not vice versa.
Raw```json ⏎ {"answer": "yes", "explanation": "In clean and onion architecture, the core of the system (inner layers) contains the business logic and dependencies point inward, meaning outer layers depend on inner layers, not vice versa."} ⏎ ``` | верно | Чистая (Robert C. Martin), луковичная (Jeffrey Palermo) и гексагональная (ports & adapters) — варианты одной идеи: зависимости направлены внутрь, к домену. Слоями в проекте следит deptrac. |
T25-L2 0.37 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 to maintain separation of concerns, relying only on the language and standard library.
Raw{"answer": "yes", "explanation": "Domain entities should be framework-agnostic to maintain separation of concerns, relying only on the language and standard library."} | верно | Изоляция домена от инфраструктуры; 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 Twig templates belong to the presentation layer, not the business-logic layer.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "Controllers and Twig templates belong to the presentation layer, not the business-logic layer." ⏎ } | верно | Наоборот: это интерфейсные адаптеры (внешний слой); они зависят от use cases, а не наоборот. |
T25-L4 0.39 c | Clean architecture | What sits at the very center of the onion architecture? | «domain» Пояснение: In Onion Architecture, the Domain layer is placed at the very center, containing the business rules and core logic, surrounded by Application, Infrastructure, and Presentation layers.
Raw{"answer": "Domain", "explanation": "In Onion Architecture, the Domain layer is placed at the very center, containing the business rules and core logic, surrounded by Application, Infrastructure, and Presentation layers."} | неверно верный: «domain model» | Центральное кольцо — Domain Model: сущности и бизнес-правила без зависимостей; далее Domain Services → Application Services → Infrastructure/UI/Tests (Palermo). |
T25-L5 0.37 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 explicitly define layer boundaries and fail the build if a layer makes a forbidden dependency call to another layer.
Raw{"answer": "yes", "explanation": "Tools like Deptrac explicitly define layer boundaries and fail the build if a layer makes a forbidden dependency call to another layer."} | верно | depfile.yaml в проекте TasK: CI проверяет правила слоёв на каждом пайплайне. |
T25-L6 0.79 c | Clean architecture | A use case (interactor) may accept an HTTP request or an EntityManager as arguments — it is simpler that way. | «yes» Пояснение: In practical application design, injecting concrete interfaces like EntityManager (which is an interface in many ORMs) or standard data transfer objects representing the request into a service or use case (interactor) is a common and valid dependency injection pattern to maintain loose coupling.
Raw```json ⏎ {"answer": "yes", "explanation": "In practical application design, injecting concrete interfaces like EntityManager (which is an interface in many ORMs) or standard data transfer objects representing the request into a service or use case (interactor) is a common and valid dependency injection pattern to maintain loose coupling."} ⏎ ``` | неверно верный: «no» | Use case принимает DTO и порты; привязка к HTTP/ORM протекает инфраструктуру во внутренние слои. |
T25-L7 0.72 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 PHP (and many other frameworks/languages), a Repository encapsulates the set of objects that can be thought of as a collection (e.g. a database table) and provides methods for accessing and manipulating that collection, hiding the underlying storage details behind an interface.
Raw{"answer": "Repository", "explanation": "In PHP (and many other frameworks/languages), a Repository encapsulates the set of objects that can be thought of as a collection (e.g. a database table) and provides methods for accessing and manipulating that collection, hiding the underlying storage details behind an interface."} | верно | Repository pattern (DDD/Evans); в проекте — Doctrine-репозитории за портами. |
T25-L8 0.46 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), not concrete implementations like PostgreSQL, so swapping the database only affects the outer adapter/infrastructure layer.
Raw{"answer": "yes", "explanation": "In Clean Architecture, the domain and use cases depend on abstractions (interfaces), not concrete implementations like PostgreSQL, so swapping the database only affects the outer adapter/infrastructure layer."} | верно | Следствие правила зависимостей: инфраструктура взаимозаменяема. |
T26-L1 0.57 c | DDD | In DDD, an aggregate is just another name for a database table. | «no» Пояснение: In DDD, an aggregate is a cluster of related objects treated as a single unit for data changes, not merely a database table.
Raw```json ⏎ {"answer": "no", "explanation": "In DDD, an aggregate is a cluster of related objects treated as a single unit for data changes, not merely 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» Пояснение: A Value Object is defined by its immutable properties and is considered equal if its field values match, rather than by memory identity.
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "A Value Object is defined by its immutable properties and is considered equal if its field values match, rather than by memory identity." ⏎ } ⏎ ``` | верно | Классика Evans: Money, Email; равенство структурное. |
T26-L3 0.37 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 entry point through which all interactions and changes to the aggregate must pass.
Raw{ ⏎ "answer": "Root", ⏎ "explanation": "In Domain-Driven Design, the aggregate root is the single entry point through which all interactions and changes to the aggregate must pass." ⏎ } | неверно верный: «aggregate root» | Aggregate Root: внешние объекты ссылаются только на корень; он защищает инварианты агрегата. |
T26-L4 0.39 c | DDD | In DDD, a repository is declared for an aggregate (its root), not for every entity. | «yes» Пояснение: In Domain-Driven Design, repositories are specifically designed to manage aggregate roots, treating the entire aggregate as a consistent unit rather than managing individual entities within it.
Raw{"answer": "yes", "explanation": "In Domain-Driven Design, repositories are specifically designed to manage aggregate roots, treating the entire aggregate as a consistent unit rather than managing individual entities within it."} | верно | Репозиторий корня хранит границу согласованности агрегата; вложенные сущности доступны только через корень. |
T26-L5 0.37 c | DDD | Ubiquitous language is the model's shared language common to developers and domain experts. | «yes» Пояснение: Ubiquitous language is a core practice in Domain-Driven Design where the model and the domain experts use the same shared language.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Ubiquitous language is a core practice in Domain-Driven Design where the model and the domain experts use the same shared language." ⏎ } | верно | Evans: язык из требований переходит в имена классов и методов. |
T26-L6 0.44 c | DDD | What is the boundary called within which a model and its language are consistent, while outside the same words mean other models? | «context» Пояснение: In software modeling and semantics, the term 'context' defines the specific scope or environment where a model's symbols have consistent meaning, distinguishing them from how they might be interpreted in other frameworks or models.
Raw{"answer": "Context", "explanation": "In software modeling and semantics, the term 'context' defines the specific scope or environment where a model's symbols have consistent meaning, distinguishing them from how they might be interpreted in other frameworks or models."} | неверно верный: «bounded context» | Bounded Context; «Заказ» в биллинге и в доставке — разные модели. |
T26-L7 0.38 c | DDD | An anemic model (objects with only getters/setters, logic in services) is the recommended DDD style. | «no» Пояснение: DDD (Domain-Driven Design) advocates for Rich Domain Models where logic resides in entities, not anemic models with only getters/setters.
Raw{"answer": "no", "explanation": "DDD (Domain-Driven Design) advocates for Rich Domain Models where logic resides in entities, not anemic models with only getters/setters."} | верно | Наоборот: Evans называет анемичность антипаттерном — поведение должно жить в доменных объектах. |
T26-L8 0.47 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, a Bounded Context is a boundary within which a specific domain model applies, and the same ubiquitous language term can have different meanings or representations in different contexts.
Raw{"answer": "yes", "explanation": "In Domain-Driven Design, a Bounded Context is a boundary within which a specific domain model applies, and the same ubiquitous language term can have different meanings or representations in different contexts."} | верно | Модели контекстов независимы; между ними — явная интеграция (ACL, published language). |
T13-L1 0.45 c | Symfony | Services in the Symfony DI container are created lazily by default — on first use. | «no» Пояснение: Services in the Symfony DI container are created eagerly (instantiated) when the container is compiled or initialized, not lazily on first use, unless specifically configured to be lazy (e.g., using proxying).
Raw{"answer": "no", "explanation": "Services in the Symfony DI container are created eagerly (instantiated) when the container is compiled or initialized, not lazily on first use, unless specifically configured to be lazy (e.g., using proxying)."} | неверно верный: «yes» | Контейнер инстанцирует сервис при первом извлечении; eager-создания по умолчанию нет. |
T13-L2 0.25 c | Symfony | Which Symfony console command lists all registered routes? | «debug:router» Пояснение: The debug:router command lists all registered routes in a Symfony application.
Raw{"answer": "debug:router", "explanation": "The debug:router command lists all registered routes in a Symfony application."} | верно | bin/console debug:router (FrameworkBundle); в Symfony 3 команда называлась router:debug. |
T13-L3 0.49 c | Symfony | Symfony autowiring requires manually declaring every service in services.yaml. | «no» Пояснение: Symfony's autowiring feature automatically resolves dependencies based on type hints, eliminating the need to manually declare every service, although explicit configuration is still used for special cases like scalar values or interface implementation.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "Symfony's autowiring feature automatically resolves dependencies based on type hints, eliminating the need to manually declare every service, although explicit configuration is still used for special cases like scalar values or interface implementation." ⏎ } | верно | Autowire+autoconfigure регистрируют и связывают сервисы автоматически; ручное перечисление — исключение. |
T13-L4 0.34 c | Symfony | Twig templates are compiled into PHP classes and cached between requests. | «yes» Пояснение: Twig compiles templates into PHP classes and caches them (typically as .php files) to avoid recompilation on subsequent requests.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Twig compiles templates into PHP classes and caches them (typically as .php files) to avoid recompilation on subsequent requests." ⏎ } | верно | Twig компилирует шаблон один раз; кэш в var/cache/twig, в prod не пересобирается. |
T13-L5 0.45 c | Symfony | In the Symfony dev environment the DI container is rebuilt only after tracked files change, not on every request. | «no» Пояснение: In the Symfony dev environment, the DI container is checked for changes and rebuilt on every request if necessary, rather than being rebuilt only when tracked files change on a static schedule.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "In the Symfony dev environment, the DI container is checked for changes and rebuilt on every request if necessary, rather than being rebuilt only when tracked files change on a static schedule." ⏎ } ⏎ ``` | неверно верный: «yes» | 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 determines the active Symfony environment (e.g., dev, prod, test).
Raw{"answer": "APP_ENV", "explanation": "The APP_ENV environment variable determines the active Symfony environment (e.g., dev, prod, test)."} | верно | APP_ENV в .env; APP_DEBUG — отдельный флаг отладки. |
T13-L7 0.35 c | Symfony | A controller method can be private — Symfony routing works with any method of the class. | «no» Пояснение: In Symfony, controller methods invoked by the router must be public; private methods cannot be called from outside the class.
Raw{"answer": "no", "explanation": "In Symfony, controller methods invoked by the router must be public; private methods cannot be called from outside the class."} | верно | Действие контроллера должно быть public; приватный метод по маршруту не вызывается. |
T13-L8 0.58 c | Symfony | Event subscribers always receive events before listeners, because the interface gives them priority. | «no» Пояснение: In Symfony's event dispatcher, listeners and subscribers are essentially the same mechanism (subscribers implement EventSubscriberInterface to register listeners), and there is no inherent priority of one over the other; execution order depends on the priority defined for each event.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "In Symfony's event dispatcher, listeners and subscribers are essentially the same mechanism (subscribers implement EventSubscriberInterface to register listeners), and there is no inherent priority of one over the other; execution order depends on the priority defined for each event." ⏎ } | верно | Порядок определяет 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» Пояснение: In Symfony 6.0 and later, the legacy Guard system was removed in favor of the new Authenticator system based on AuthenticatorInterface, making this statement true.
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "In Symfony 6.0 and later, the legacy Guard system was removed in favor of the new Authenticator system based on AuthenticatorInterface, making this statement true." ⏎ } ⏎ ``` | верно | Guard объявлен устаревшим в 5.3 и удалён в 6.0; в проекте symfony/security-bundle 8.1. |
T22-L2 0.43 c | Symfony: Security and forms | Which Symfony attribute checks a role/permission right on a controller method (403 without it)? | «#isgranted» Пояснение: The #IsGranted attribute is used in Symfony to check if the current user has a specific role or permission, returning a 403 Forbidden error if they do not.
Raw{"answer": "#IsGranted", "explanation": "The #IsGranted attribute is used in Symfony to check if the current user has a specific role or permission, returning a 403 Forbidden error if they do not."} | верно | #[IsGranted('ROLE_ADMIN')]; атрибут из symfony/security-http. |
T22-L3 0.39 c | Symfony: Security and forms | Voters are Symfony's mechanism for checking access to a specific object: isGranted('EDIT', $post). | «yes» Пояснение: In Symfony, Voters are used to define custom authorization logic for specific objects, such as checking if a user can edit a particular post.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In Symfony, Voters are used to define custom authorization logic for specific objects, such as checking if a user can edit a particular post." ⏎ } | верно | VoterInterface->vote(); docs Symfony — Voters. |
T22-L4 0.36 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» Пояснение: Doctrine Annotations are deprecated in favor of PHP attributes, but they are still supported in Symfony 7 for validation constraints.
Raw{"answer": "no", "explanation": "Doctrine Annotations are deprecated in favor of PHP attributes, but they are still supported in Symfony 7 for validation constraints."} | неверно верный: «yes» | Докблок-аннотации удалены в Symfony 7.0; стандарт — атрибуты. В проекте symfony/validator 8.1. |
T22-L5 0.4 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 CSRF protection by default, validating a token generated with the form and submitted alongside it to prevent Cross-Site Request Forgery attacks.
Raw{"answer": "yes", "explanation": "Symfony forms include CSRF protection by default, validating a token generated with the form and submitted alongside it to prevent Cross-Site Request Forgery attacks."} | верно | FormType добавляет скрытое поле _token и проверяет его при валидации; отключение — осознанное исключение (csrf: false). |
T22-L6 0.41 c | Symfony: Security and forms | Form validation in Symfony runs server-side even if the client-side (HTML5) checks passed. | «yes» Пояснение: In Symfony, even if client-side HTML5 validation passes, the server-side validation using Symfony's validation component always runs to ensure data integrity and security.
Raw```json ⏎ {"answer": "yes", "explanation": "In Symfony, even if client-side HTML5 validation passes, the server-side validation using Symfony's validation component always runs to ensure data integrity and security."} ⏎ ``` | верно | Клиентская валидация — только удобство; серверная обязательна и идёт по метаданным объекта формы. |
T22-L7 0.4 c | Symfony: Security and forms | Which Symfony maker command generates a form class (FormType)? | «make:form» Пояснение: The Symfony MakerBundle command 'php bin/console make:form' is used to generate form classes and optionally the associated entity.
Raw{"answer": "make:form", "explanation": "The Symfony MakerBundle command 'php bin/console make:form' is used to generate form classes and optionally the associated entity."} | верно | bin/console make:form (symfony/maker-bundle — в проекте). |
T22-L8 0.29 c | Symfony: Security and forms | Symfony stores the user's password in the session in plain text. | «no» Пояснение: Symfony stores the user's password hash in the session, not the plain text password.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "Symfony stores the user's password hash in the session, not the plain text password." ⏎ } ⏎ ``` | верно | В сессии живёт объект пользователя в токене; хеш затирается eraseCredentials(), plaintext там никогда не лежит. |
T23-L1 0.39 c | Symfony: configuration and services | Symfony bundle configuration lives in config/packages — one file per bundle or topic. | «yes» Пояснение: In modern Symfony projects (using Flex), configuration files are typically organized in the config/packages directory, with one file per bundle or specific topic.
Raw{"answer": "yes", "explanation": "In modern Symfony projects (using Flex), configuration files are typically organized in the config/packages directory, with one file per bundle or specific topic."} | верно | Стандартная структура (config/packages/*.yaml); перегрузка — config/packages/<env>. |
T23-L2 0.5 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» Пояснение: In typical PHP development workflows, a .env file containing default development values is often committed to version control for convenience, while .env.local (or .env) containing specific secrets is added to .gitignore to prevent them from being committed.
Raw{"answer": "yes", "explanation": "In typical PHP development workflows, a .env file containing default development values is often committed to version control for convenience, while .env.local (or .env) containing specific secrets is added to .gitignore to prevent them from being committed."} | верно | symfony/dotenv: .env — общий безопасный набор значений; локальные секреты — .env.local (gitignored) или secrets-хранилище. |
T23-L3 0.44 c | Symfony: configuration and services | Which Symfony command lists the container's registered services and their aliases? | «debug:container» Пояснение: The 'debug:console' command is used to debug console commands, while 'debug:container' is used to debug and list the container's services and their aliases.
Raw{"answer": "debug:container", "explanation": "The 'debug:console' command is used to debug console commands, while 'debug:container' is used to debug and list the container's services and their aliases."} | верно | bin/console debug:container; параметры контейнера — debug:parameter. |
T23-L4 0.65 c | Symfony: configuration and services | The Symfony container allows changing parameters at runtime: $container->setParameter() works from a controller. | «no» Пояснение: Once the container is compiled, it is frozen, and changing parameters with setParameter() at runtime (e.g., in a controller) generally has no effect on services that already received the parameter during instantiation, nor is it the intended mechanism for dynamic behavior.
Raw{"answer": "no", "explanation": "Once the container is compiled, it is frozen, and changing parameters with setParameter() at runtime (e.g., in a controller) generally has no effect on services that already received the parameter during instantiation, nor is it the intended mechanism for dynamic behavior."} | верно | Контейнер компилируется и замораживается; runtime-значения — только через переменные окружения. |
T23-L5 0.42 c | Symfony: configuration and services | By default, Symfony services are public (public: true) — you can fetch them directly from the container. | «no» Пояснение: Since Symfony 4, all services are private (public: false) by default and must be explicitly marked as public to be fetched directly from the container.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "Since Symfony 4, all services are private (public: false) by default and must be explicitly marked as public to be fetched directly from the container." ⏎ } | верно | С Symfony 4.0 сервисы по умолчанию private: инжектятся через autowiring; $container->get() — только для публичных. |
T23-L6 0.45 c | Symfony: configuration and services | Without a config file in config/packages a bundle will not work — configuration is mandatory for every bundle. | «no» Пояснение: Bundles do not strictly require a configuration file in config/packages to work, as they can rely on default values defined in their Configuration class or be used without configuration.
Raw{"answer": "no", "explanation": "Bundles do not strictly require a configuration file in config/packages to work, as they can rely on default values defined in their Configuration class or be used without configuration."} | верно | У бандлов есть встроенные умолчания (Extension); конфиг нужен только для отклонений от них. |
T23-L7 0.33 c | Symfony: configuration and services | Environment variable values are injected into services.yaml using the %env(VAR)% syntax. | «yes» Пояснение: Symfony uses the %env(VAR_NAME)% syntax to inject environment variables into parameter definitions within configuration files like services.yaml.
Raw{"answer": "yes", "explanation": "Symfony uses the %env(VAR_NAME)% syntax to inject environment variables into parameter definitions within configuration files like services.yaml."} | верно | %env(...)% резолвится в рантайме env-процессорами; docs — Env Var Processors. |
T23-L8 0.37 c | Symfony: configuration and services | Which Symfony environment variable enables debug mode (affects the profiler and Twig debugging)? | «app_debug» Пояснение: In the default Symfony skeleton, the APP_DEBUG environment variable controls debug mode, which enables the profiler and Twig debugging features.
Raw{"answer": "APP_DEBUG", "explanation": "In the default Symfony skeleton, the APP_DEBUG environment variable controls debug mode, which enables the profiler and Twig debugging features."} | верно | APP_DEBUG=1 (в .env dev-окружения); окружение выбирает APP_ENV — см. T13-L6. |
T16-L1 0.51 c | Symfony: Messenger | A single message in Symfony Messenger can only have one handler. | «no» Пояснение: In Symfony Messenger, a single message can be processed by multiple handlers if the message's metadata or the message bus configuration allows multiple handlers to be registered for that specific message type.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "In Symfony Messenger, a single message can be processed by multiple handlers if the message's metadata or the message bus configuration allows multiple handlers to be registered for that specific message type." ⏎ } ⏎ ``` | верно | Messenger вызывает все хендлеры, подписанные на класс сообщения (docs — Multiple Handlers). |
T16-L2 0.31 c | Symfony: Messenger | The sync transport in Messenger queues the message for a worker, just like async. | «no» Пояснение: The sync transport executes the handler immediately in the current process, whereas async transports defer execution to a worker process.
Raw{"answer": "no", "explanation": "The sync transport executes the handler immediately in the current process, whereas async transports defer execution to a worker process."} | верно | Наоборот: sync обрабатывает немедленно в том же процессе, что и отправка; очередь — это async-транспорт. |
T16-L3 0.31 c | Symfony: Messenger | Which console command starts the worker that processes Messenger queue messages? | «php bin/console messenger:consume» Пояснение: This command starts the worker to process messages in the Symfony Messenger queue.
Raw{"answer": "php bin/console messenger:consume", "explanation": "This command starts the worker to process messages in the Symfony Messenger queue."} | верно | bin/console messenger:consume async; воркеры под supervisord/systemd в проде. |
T16-L4 0.49 c | Symfony: Messenger | Retries for failed messages (retry_strategy) are configured per Messenger transport. | «yes» Пояснение: In Symfony's Messenger component, the retry strategy (including max number of tries, delay, and multiplier) is indeed configured per transport in the framework's configuration (e.g., messenger.transports).
Raw{"answer": "yes", "explanation": "In Symfony's Messenger component, the retry strategy (including max number of tries, delay, and multiplier) is indeed configured per transport in the framework's configuration (e.g., messenger.transports)."} | верно | retry_strategy на транспорте: max_retries, delay, multiplier; docs — Failed Messages & Retries. |
T16-L5 0.31 c | Symfony: Messenger | By default, Messenger serializes messages to JSON. | «yes» Пояснение: By default, Messenger serializes messages to JSON using the Serializer component.
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "By default, Messenger serializes messages to JSON using the Serializer component." ⏎ } ⏎ ``` | неверно верный: «no» | Дефолтный сериализатор — PhpSerializer (serialize()); JSON-сериализатор включается отдельно. |
T16-L6 0.33 c | Symfony: Messenger | Symfony Scheduler produces messages on a schedule and dispatches them through Messenger. | «yes» Пояснение: The Symfony Scheduler component integrates with the Messenger component to allow scheduling jobs that are dispatched as messages.
Raw{"answer": "yes", "explanation": "The Symfony Scheduler component integrates with the Messenger component to allow scheduling jobs that are dispatched as messages."} | верно | Schedule → RecurringMessage → шина Messenger; docs — Scheduler. |
T16-L7 0.25 c | Symfony: Messenger | Which built-in Messenger transport stores messages in database tables via Doctrine? | «doctrine» Пояснение: The built-in Messenger transport that stores messages in database tables using Doctrine is called 'doctrine'.
Raw{"answer": "doctrine", "explanation": "The built-in Messenger transport that stores messages in database tables using Doctrine is called 'doctrine'."} | верно | Транспорт doctrine (symfony/doctrine-messenger); таблица messenger_messages. В проекте стоит amqp-messenger + doctrine-messenger. |
T16-L8 0.37 c | Symfony: Messenger | The Messenger pipeline can be extended with custom middleware, placed before or after the built-in ones. | «yes» Пояснение: Symfony's Messenger component allows the addition of custom middleware, enabling developers to extend the pipeline at various points.
Raw```json ⏎ {"answer": "yes", "explanation": "Symfony's Messenger component allows the addition of custom middleware, enabling developers to extend the pipeline at various points."} ⏎ ``` | верно | messenger.bus.*.middleware в yaml; docs — Middleware. |
T28-L1 0.36 c | Symfony: versions | Symfony major releases come every two years, minor ones every six months (in May and November). | «yes» Пояснение: Symfony releases major versions every two years (e.g., 5.0, 6.0, 7.0) and minor versions every six months in May and November.
Raw{"answer": "yes", "explanation": "Symfony releases major versions every two years (e.g., 5.0, 6.0, 7.0) and minor versions every six months in May and November."} | верно | Стандартный релизный цикл: 8.0 — ноябрь 2025, 8.1 — май 2026, 8.2 — ноябрь 2026. |
T28-L2 0.29 c | Symfony: versions | What is the minimum PHP version required by Symfony 8? | «8.4» Пояснение: Symfony 8 requires PHP 8.4 or later as its minimum supported version.
Raw{ ⏎ "answer": 8.4, ⏎ "explanation": "Symfony 8 requires PHP 8.4 or later as its minimum supported version." ⏎ } | верно | Symfony 8.0 поднял требование до PHP >= 8.4.1 (в vendor проекта: "php": ">=8.4.1"). |
T28-L3 0.23 c | Symfony: versions | Symfony 7.0 kept support for docblock annotations (validation, routes). | «no» Пояснение: Symfony 7.0 removed support for docblock annotations in favor of native attributes.
Raw{"answer": "no", "explanation": "Symfony 7.0 removed support for docblock annotations in favor of native attributes."} | верно | Наоборот: в 7.0 аннотации удалены — только PHP-атрибуты (#[Route], #[Assert\NotBlank]). |
T28-L4 0.45 c | Symfony: versions | AssetMapper manages CSS/JS without node or webpack — via importmap.php. | «yes» Пояснение: Symfony's AssetMapper is a lightweight component that handles JavaScript and CSS assets using only PHP and an importmap.php file, eliminating the need for Node.js and Webpack.
Raw{"answer": "yes", "explanation": "Symfony's AssetMapper is a lightweight component that handles JavaScript and CSS assets using only PHP and an importmap.php file, eliminating the need for Node.js and Webpack."} | верно | symfony/asset-mapper (с 6.3, стандарт с 7.x); в проекте — importmap.php в корне и asset-mapper 8.1. |
T28-L5 0.22 c | Symfony: versions | Symfony 6.4 is a regular release without long-term support. | «no» Пояснение: Symfony 6.4 is an LTS (Long-Term Support) release.
Raw{"answer": "no", "explanation": "Symfony 6.4 is an LTS (Long-Term Support) release."} | верно | Наоборот: 6.4 — LTS (расширенная поддержка); LTS выходит вместе с очередным мажором (6.4 — вместе с 7.0). |
T28-L6 0.45 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» Пояснение: In Symfony's policy, features and classes deprecated in a major version (e.g., 5.x) are removed in the next major version (e.g., 6.x), not kept working.
Raw{"answer": "no", "explanation": "In Symfony's policy, features and classes deprecated in a major version (e.g., 5.x) are removed in the next major version (e.g., 6.x), not kept working."} | верно | Наоборот: мажорный релиз удаляет всё устаревшее (7.0 убрал деприкейшены 6.x, 8.0 — 7.x). |
T28-L7 0.34 c | Symfony: versions | Every Symfony major release is accompanied by an UPGRADE guide listing the changes. | «yes» Пояснение: Each major Symfony release includes an UPGRADE document that details deprecations and breaking changes.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Each major Symfony release includes an UPGRADE document that details deprecations and breaking changes." ⏎ } | верно | UPGRADE-7.0.md, UPGRADE-8.0.md в репозитории symfony/symfony. |
T28-L8 0.55 c | Symfony: versions | Which Symfony component manages assets and the importmap without node/webpack? | «webpack-encore» Пояснение: Webpack-Encore is the component used in Symfony to manage assets and importmaps, providing a simple API for configuring and using Webpack without needing to manage node or webpack directly.
Raw{"answer": "Webpack-Encore", "explanation": "Webpack-Encore is the component used in Symfony to manage assets and importmaps, providing a simple API for configuring and using Webpack without needing to manage node or webpack directly."} | неверно верный: «asset-mapper» | symfony/asset-mapper 8.1 — в проекте. |
T29-L1 4.45 c | Symfony: 8.2 and beyond | As of 2026-11-07, Symfony 8.2 has already been released. | «no» Пояснение: Symfony releases major versions in even years (e.g., 7.0 in 2024, 8.0 in 2025); minor versions like 8.2 would appear after the major 8.0 release, making 8.2 available in late 2025 or 2026, but the prompt claims it has *already* been released as of Nov 2026. However, Symfony 8.0 is expected in November 2025, and 8.2 would be a point release typically released a few months after 8.0. Given the rapid release cycle (minor every ~3-4 months), 8.2 is plausible, but the standard major release for 2026 is 8.0. Wait, Symfony releases: 6.4 LTS (Nov 2023), 7.0 (Nov 2024), 8.0 (Nov 2025). Minor versions 7.1, 7.2, 7.3 follow 7.0. So 8.0 is Nov 2025. 8.1 would be early 2026, 8.2 mid/late 2026. So by Nov 2026, 8.2 is likely released. However, the question is a bit tricky. Let's look at the pattern. Symfony 6.2 was released May 2023. Symfony 6.4 was Nov 2023. Symfony 7.0 was Nov 2024. Symfony 7.2 was likely late 2025? No, 7.0 is Nov 2024. 7.1, 7.2, 7.3 are the minors for the 7.x line. 8.0 is Nov 2025. Then 8.1, 8.2, 8.3 are minors for 8.x. 8.2 would be around May/June 2026. So by Nov 2026, it is released. True. Wait, let's re-verify the release cycle. Major versions are annual. 7.0 in Nov 2024. 8.0 in Nov 2025. Minor versions are roughly quarterly or bi-monthly. 7.1, 7.2, 7.3. If 7.0 is Nov 2024, 7.3 is Nov 2025 (LTS). 8.0 is Nov 2025. 8.1, 8.2, 8.3 (LTS) by Nov 2026. So 8.2 would be around May/June 2026. So by Nov 7, 2026, it is released. True.
Raw{"answer": "no", "explanation": "Symfony releases major versions in even years (e.g., 7.0 in 2024, 8.0 in 2025); minor versions like 8.2 would appear after the major 8.0 release, making 8.2 available in late 2025 or 2026, but the prompt claims it has *already* been released as of Nov 2026. However, Symfony 8.0 is expected in November 2025, and 8.2 would be a point release typically released a few months after 8.0. Given the rapid release cycle (minor every ~3-4 months), 8.2 is plausible, but the standard major release for 2026 is 8.0. Wait, Symfony releases: 6.4 LTS (Nov 2023), 7.0 (Nov 2024), 8.0 (Nov 2025). Minor versions 7.1, 7.2, 7.3 follow 7.0. So 8.0 is Nov 2025. 8.1 would be early 2026, 8.2 mid/late 2026. So by Nov 2026, 8.2 is likely released. However, the question is a bit tricky. Let's look at the pattern. Symfony 6.2 was released May 2023. Symfony 6.4 was Nov 2023. Symfony 7.0 was Nov 2024. Symfony 7.2 was likely late 2025? No, 7.0 is Nov 2024. 7.1, 7.2, 7.3 are the minors for the 7.x line. 8.0 is Nov 2025. Then 8.1, 8.2, 8.3 are minors for 8.x. 8.2 would be around May/June 2026. So by Nov 2026, it is released. True. Wait, let's re-verify the release cycle. Major versions are annual. 7.0 in Nov 2024. 8.0 in Nov 2025. Minor versions are roughly quarterly or bi-monthly. 7.1, 7.2, 7.3. If 7.0 is Nov 2024, 7.3 is Nov 2025 (LTS). 8.0 is Nov 2025. 8.1, 8.2, 8.3 (LTS) by Nov 2026. So 8.2 would be around May/June 2026. So by Nov 7, 2026, it is released. True."} | верно | Наоборот: 8.2 ещё не выпущена — релиз в конце ноября 2026; последняя стабильная — 8.1. |
T29-L2 0.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. | «yes» Пояснение: Symfony minor versions are released every 6 months, so following the standard cycle from 7.1 (November 2025) or 7.2 (May 2026), 8.2 would align with the November 2026 release window.
Raw{"answer": "yes", "explanation": "Symfony minor versions are released every 6 months, so following the standard cycle from 7.1 (November 2025) or 7.2 (May 2026), 8.2 would align with the November 2026 release window."} | верно | Политика релизов: 8.1 — май 2026, 8.2 — ноябрь 2026; якорь даты фиксирует срез — модель с поздним cutoff отвечает «на дату». |
T29-L3 0.36 c | Symfony: 8.2 and beyond | Which Symfony version comes after 8.1 (as of 2026-11-07)? | «8.2» Пояснение: Symfony follows a minor version increment pattern, so the version after 8.1 is 8.2.
Raw{"answer": "8.2", "explanation": "Symfony follows a minor version increment pattern, so the version after 8.1 is 8.2."} | верно | 8.2 — следующий минорный релиз (ноябрь 2026); после его выхода проект переходит с 8.1.* на 8.2.*. |
T29-L4 0.72 c | Symfony: 8.2 and beyond | Symfony 8.2 is a major release requiring applications to be rewritten for new APIs. | «no» Пояснение: Symfony is a stable major framework (currently in the 7.x line, with 8.0 planned but not yet a 'major rewrite' release); major versions maintain backward compatibility within the version, and 8.2 implies a minor release within the 8.x major line, not a complete rewrite.
Raw{"answer": "no", "explanation": "Symfony is a stable major framework (currently in the 7.x line, with 8.0 planned but not yet a 'major rewrite' release); major versions maintain backward compatibility within the version, and 8.2 implies a minor release within the 8.x major line, not a complete rewrite."} | верно | Наоборот: 8.2 — минорный релиз; новые возможности без поломки обратной совместимости. Мажор — 9.0. |
T29-L5 0.41 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 follows Semantic Versioning where the minor version (e.g., 8.1 to 8.2) promises backward compatibility without breaking changes, so no code changes are strictly required.
Raw{"answer": "yes", "explanation": "PHP follows Semantic Versioning where the minor version (e.g., 8.1 to 8.2) promises backward compatibility without breaking changes, so no code changes are strictly required."} | верно | Политика Symfony: минорные релизы обратно совместимы; BC-break допустим только в мажорных. |
T29-L6 0.39 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 series before the major release of Symfony 9.0.
Raw{"answer": 8.4, "explanation": "Symfony 8.4 is the final minor release in the 8.x series before the major release of Symfony 9.0."} | верно | По циклу: 8.2 (ноя 2026), 8.3 (май 2027), 8.4 (ноя 2027, вместе с 9.0) — как 6.4 выходила вместе с 7.0. |
T29-L7 0.62 c | Symfony: 8.2 and beyond | Symfony 8.2 will require PHP 8.5 — you would have to upgrade PHP along with it. | «yes» Пояснение: The statement describes a hypothetical future version (Symfony 8.2) and a future PHP version (PHP 8.5), but in the context of such questions, it is typically treated as a factual assertion about the dependency relationship, making it True.
Raw{"answer": "yes", "explanation": "The statement describes a hypothetical future version (Symfony 8.2) and a future PHP version (PHP 8.5), but in the context of such questions, it is typically treated as a factual assertion about the dependency relationship, making it True."} | неверно верный: «no» | Наоборот: минорные релизы не поднимают требования PHP; для всей ветки 8.x остаётся PHP >= 8.4. |
T29-L8 0.51 c | Symfony: 8.2 and beyond | Deprecations added in the 8.x branch will not be removed before Symfony 9.0. | «yes» Пояснение: According to Symfony's deprecation policy, features deprecated in a major version (like 8.x) are guaranteed to remain for at least one subsequent major version (9.0) before they can be removed, ensuring backward compatibility and a clear migration path.
Raw{"answer": "yes", "explanation": "According to Symfony's deprecation policy, features deprecated in a major version (like 8.x) are guaranteed to remain for at least one subsequent major version (9.0) before they can be removed, ensuring backward compatibility and a clear migration path."} | верно | Политика: деприкейшены живут до следующего мажора; 9.0 — ноябрь 2027. |
T21-L1 0.47 c | Twig | Inside {{ }}, Twig allows calling arbitrary PHP code directly. | «no» Пояснение: In Twig, {{ }} is used for outputting variables and simple expressions (like function calls and operators), but not for arbitrary PHP code directly.
Raw```json ⏎ {"answer": "no", "explanation": "In Twig, {{ }} is used for outputting variables and simple expressions (like function calls and operators), but not for arbitrary PHP code directly."} ⏎ ``` | верно | Twig — DSL: только разрешённые окружением функции/фильтры; произвольный PHP не исполняется. |
T21-L2 0.28 c | Twig | By default, Twig auto-escapes printed variables. | «yes» Пояснение: By default, Twig automatically escapes output to protect against HTML injection attacks.
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "By default, Twig automatically escapes output to protect against HTML injection attacks." ⏎ } ⏎ ``` | верно | Autoescape включён по умолчанию; {{ '<b>' }} → <b>. Проверено на Twig 3.30. |
T21-L3 0.37 c | Twig | The Twig |e filter escapes a string for safe output in an HTML context. | «yes» Пояснение: The |e filter (short for |escape) defaults to the 'html' strategy, which safely escapes special characters for HTML output.
Raw{"answer": "yes", "explanation": "The |e filter (short for |escape) defaults to the 'html' strategy, which safely escapes special characters for HTML output."} | верно | |e ('html') по умолчанию; есть контексты js/url/css. От SQL-инъекций он не защищает — это задача подготовленных запросов Doctrine. |
T21-L4 0.27 c | Twig | Which filter from twig/intl-extra formats a number according to a locale? | «number_format» Пояснение: The twig/intl-extra package provides the number_format filter to format numbers according to a specified locale.
Raw{ ⏎ "answer": "number_format", ⏎ "explanation": "The twig/intl-extra package provides the number_format filter to format numbers according to a specified locale." ⏎ } | неверно верный: «format_number» | |format_number(locale=...) из IntlExtension (twig/intl-extra есть в проекте). Проверено на Twig 3.30: 12345.6 → 12 345,6 (ru). |
T21-L5 0.47 c | Twig | The |raw filter disables auto-escaping for the value. | «yes» Пояснение: The |raw filter in PHP templating engines like Twig or Laravel Blade explicitly marks a variable as raw, preventing automatic HTML entity encoding (escaping).
Raw{"answer": "yes", "explanation": "The |raw filter in PHP templating engines like Twig or Laravel Blade explicitly marks a variable as raw, preventing automatic HTML entity encoding (escaping)."} | верно | {{ x|raw }} выводит HTML как есть; опасно с пользовательскими данными. Проверено на Twig 3.30. |
T21-L6 0.39 c | Twig | In Twig, {{ }} prints an expression value, while {% %} executes tags — conditions, loops, set. | «yes» Пояснение: In Twig, double curly braces {{ }} are used to output expression values, while single percent signs {% %} are used for executing statements like loops, conditions, and variable assignments.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In Twig, double curly braces {{ }} are used to output expression values, while single percent signs {% %} are used for executing statements like loops, conditions, and variable assignments." ⏎ } | верно | Два блока синтаксиса Twig: вывод (echo) против логики. |
T21-L7 0.32 c | Twig | In Twig you cannot declare a variable inside a template — values only come from the controller. | «no» Пояснение: Twig allows declaring variables directly in templates using the {% set %} tag.
Raw{"answer": "no", "explanation": "Twig allows declaring variables directly in templates using the {% set %} tag."} | верно | {% set y = ... %} объявляет переменную в шаблоне. Проверено на Twig 3.30. |
T21-L8 0.35 c | Twig | Which Twig function dumps the debug structure of a variable (array, object)? | «dump» Пояснение: The 'dump' Twig function is used to display a detailed debug representation of a variable's structure and content.
Raw{"answer": "dump", "explanation": "The 'dump' Twig function is used to display a detailed debug representation of a variable's structure and content."} | верно | {{ dump(x) }} (DebugExtension; в Symfony доступна в dev-окружении). |
T24-L1 0.47 c | Bootstrap | Bootstrap is a CSS/JS library of ready-made UI components, not an SPA framework. | «yes» Пояснение: Bootstrap is a frontend framework designed to provide reusable HTML, CSS, and JavaScript components, whereas Single Page Application (SPA) frameworks like React, Vue, or Angular handle client-side routing and state management.
Raw{"answer": "yes", "explanation": "Bootstrap is a frontend framework designed to provide reusable HTML, CSS, and JavaScript components, whereas Single Page Application (SPA) frameworks like React, Vue, or Angular handle client-side routing and state management."} | верно | Компоненты и утилиты поверх вашего 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 fixed-width container that adjusts its maximum width at different breakpoints.
Raw{"answer": "container", "explanation": "The 'container' class in Bootstrap provides a responsive fixed-width container that adjusts its maximum width at different breakpoints."} | верно | .container (фиксированная макс-ширина по брейкпоинтам) vs .container-fluid (на всю ширину). |
T24-L3 0.39 c | Bootstrap | The Bootstrap grid is built on CSS floats and splits a row into 16 columns. | «no» Пояснение: The modern Bootstrap grid (v4 and later) is built on CSS flexbox and divides rows into 12 columns, not 16 or floats.
Raw{"answer": "no", "explanation": "The modern Bootstrap grid (v4 and later) is built on CSS flexbox and divides rows into 12 columns, not 16 or floats."} | верно | Наоборот: flexbox (с Bootstrap 4) и 12 колонок; float-сетка — это Bootstrap 3. |
T24-L4 0.27 c | Bootstrap | Bootstrap's named breakpoints (the infix used in class names) are sm, md, lg, xl, xxl — five of them. | «yes» Пояснение: Bootstrap 4 and later versions include exactly five named breakpoints: sm, md, lg, xl, and xxl.
Raw{"answer": "yes", "explanation": "Bootstrap 4 and later versions include exactly five named breakpoints: sm, md, lg, xl, and xxl."} | верно | Тиров всего шесть: xs (без инфикса) + пять именованных (576/768/992/1200/1400 px). |
T24-L5 3.76 c | Bootstrap | Utilities like .mt-3 or .px-2 use the spacing scale: the number is a multiple of $spacer. | «no» Пояснение: In Bootstrap, the number in spacing utilities (e.g., .mt-3) represents a multiple of the base $spacer variable, not a fixed arbitrary multiplier, though the statement is technically describing the mechanism correctly; however, usually these questions imply if it is *always* a direct integer multiple of the base $spacer without modification, which is true, but let's re-read carefully: 'the number is a multiple of $spacer' is the definition. Wait, the standard definition is that `1` equals `$spacer` (typically 1rem). So `3` equals `3 * $spacer`. This statement is actually **True**. Let me double-check if there's a trick. 'Utilities like .mt-3... use the spacing scale: the number is a multiple of $spacer.' Yes, this is the core definition of Bootstrap's spacing scale.
*Correction*: Often in these tests, if the statement is slightly off or implies something false, it's false. But this looks like the standard definition. Let's look at the phrasing again. Is it possible the question implies the number is the *value* rather than the *multiplier*? No, 'the number is a multiple of $spacer' means `N = k * $spacer`. This is correct.
Wait, looking at common PHP/CSS quizzes, sometimes they trick you with 'is equal to' vs 'is a multiple of'. Here it says 'is a multiple of'. This is correct.
Let's consider if the question is from a specific context where $spacer is not the base. In Bootstrap, `$spacer: 1rem !default;` and `.mt-3` is `margin-top: calc(#{$spacer} * 3) !default;`. So yes, it is a multiple.
However, if I must answer Yes/No, and the prompt is 'True or false?', I will say **yes** (True).
Let's re-evaluate if there is a common false statement. 'The number *is* $spacer' (False). 'The number is a *multiple* of $spacer' (True).
Answer: yes.
Raw{"answer": "no", "explanation": "In Bootstrap, the number in spacing utilities (e.g., .mt-3) represents a multiple of the base $spacer variable, not a fixed arbitrary multiplier, though the statement is technically describing the mechanism correctly; however, usually these questions imply if it is *always* a direct integer multiple of the base $spacer without modification, which is true, but let's re-read carefully: 'the number is a multiple of $spacer' is the definition. Wait, the standard definition is that `1` equals `$spacer` (typically 1rem). So `3` equals `3 * $spacer`. This statement is actually **True**. Let me double-check if there's a trick. 'Utilities like .mt-3... use the spacing scale: the number is a multiple of $spacer.' Yes, this is the core definition of Bootstrap's spacing scale. \n\n*Correction*: Often in these tests, if the statement is slightly off or implies something false, it's false. But this looks like the standard definition. Let's look at the phrasing again. Is it possible the question implies the number is the *value* rather than the *multiplier*? No, 'the number is a multiple of $spacer' means `N = k * $spacer`. This is correct.\n\nWait, looking at common PHP/CSS quizzes, sometimes they trick you with 'is equal to' vs 'is a multiple of'. Here it says 'is a multiple of'. This is correct. \n\nLet's consider if the question is from a specific context where $spacer is not the base. In Bootstrap, `$spacer: 1rem !default;` and `.mt-3` is `margin-top: calc(#{$spacer} * 3) !default;`. So yes, it is a multiple.\n\nHowever, if I must answer Yes/No, and the prompt is 'True or false?', I will say **yes** (True).\n\nLet's re-evaluate if there is a common false statement. 'The number *is* $spacer' (False). 'The number is a *multiple* of $spacer' (True).\n\nAnswer: yes."} | верно | Spacing utilities; $spacer = 1rem. |
T24-L6 0.36 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 enable interactive behaviors like dropdowns, modals, and tooltips on elements.
Raw{"answer": "data-bs-toggle", "explanation": "The data-bs-toggle attribute is used in Bootstrap 5 to enable interactive behaviors like dropdowns, modals, and tooltips on elements."} | верно | data-bs-toggle="dropdown" и т.п.; в Bootstrap 4 атрибут назывался data-toggle. |
T24-L7 0.3 c | Bootstrap | Bootstrap 5 components work without jQuery — in plain vanilla JS. | «yes» Пояснение: Bootstrap 5 replaced jQuery with vanilla JavaScript for all its interactive components.
Raw{"answer": "yes", "explanation": "Bootstrap 5 replaced jQuery with vanilla JavaScript for all its interactive components."} | верно | jQuery удалён в Bootstrap 5.0: data-bs-* атрибуты и JS API. В проекте vendored 5.3.3. |
T24-L8 0.31 c | Bootstrap | Dark mode in Bootstrap is enabled with a .dark class on the root element. | «yes» Пояснение: In Bootstrap 5, enabling dark mode is done by adding the .dark class to the <html> (root) element.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In Bootstrap 5, enabling dark mode is done by adding the .dark class to the <html> (root) element." ⏎ } | неверно верный: «no» | Наоборот: тема включается атрибутом data-bs-theme="dark" (Color modes, с 5.3); класса .dark не существует. В проекте 5.3.3. |
T14-L1 0.37 c | Doctrine | Doctrine ORM creates database tables on the fly the first time an entity is used at runtime. | «no» Пояснение: Doctrine ORM does not auto-create tables; schema changes require running tools like 'doctrine:schema:update' or migrations.
Raw{"answer": "no", "explanation": "Doctrine ORM does not auto-create tables; schema changes require running tools like 'doctrine:schema:update' or migrations."} | верно | Схему создают инструменты (migrations, schema tool); рантайм структуру БД не меняет. |
T14-L2 0.41 c | Doctrine | Which EntityManager method marks a new object as managed without executing SQL until flush()? | «persist» Пояснение: The persist method in Doctrine's EntityManager adds an entity to the persistence context without immediately executing SQL, deferring the INSERT operation until flush is called.
Raw{"answer": "persist", "explanation": "The persist method in Doctrine's EntityManager adds an entity to the persistence context without immediately executing SQL, deferring the INSERT operation until flush is called."} | верно | persist() регистрирует объект в Unit of Work; INSERT выполняется на flush(). |
T14-L3 0.71 c | Doctrine | In Doctrine ORM 3, the EntityManager::merge() method exists and makes the passed object managed. | «no» Пояснение: In Doctrine ORM 3, the EntityManager::merge() method was removed; to make a detached entity managed, you must first use the persist() method (or use the new EntityManagerInterface::persist with appropriate flags), but specifically merge is not part of the ORM 3 API.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "In Doctrine ORM 3, the EntityManager::merge() method was removed; to make a detached entity managed, you must first use the persist() method (or use the new EntityManagerInterface::persist with appropriate flags), but specifically merge is not part of the ORM 3 API." ⏎ } | верно | В ORM 3 merge() удалён (в vendor проекта 3.7.6 метода нет); в Doctrine 2.x merge() возвращал управляемую копию. Версия зафиксирована — ORM 3. |
T14-L4 0.32 c | Doctrine | DQL queries are written in terms of entities and their fields, not tables and columns. | «yes» Пояснение: DQL (Doctrine Query Language) operates at the object level, referencing entities and their properties rather than database tables and columns.
Raw{"answer": "yes", "explanation": "DQL (Doctrine Query Language) operates at the object level, referencing entities and their properties rather than database 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» Пояснение: The find method in Doctrine repositories returns null if no entity is found with the given ID.
Raw{"answer": "null", "explanation": "The find method in Doctrine repositories returns null if no entity is found with the given ID."} | верно | find() возвращает null, если объект не найден (docs Repository methods). |
T14-L6 0.43 c | Doctrine | DoctrineBundle in Symfony automatically calls flush() at the end of every request. | «yes» Пояснение: By default, DoctrineBundle is configured with `auto_commit: true`, which triggers an automatic `flush()` and `clear()` at the end of each request lifecycle.
Raw{"answer": "yes", "explanation": "By default, DoctrineBundle is configured with `auto_commit: true`, which triggers an automatic `flush()` and `clear()` at the end of each request lifecycle."} | неверно верный: «no» | Авто-flush нет — flush() зовёт разработчик; незакрытая транзакция в конце запроса откатывается. |
T14-L7 0.51 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» Пояснение: In ORM frameworks like Doctrine, once an entity is managed (i.e., persisted and tracked by the Unit of Work), any changes to its properties are detected, and flush() commits these modifications without needing to call persist() again.
Raw{"answer": "yes", "explanation": "In ORM frameworks like Doctrine, once an entity is managed (i.e., persisted and tracked by the Unit of Work), any changes to its properties are detected, and flush() commits these modifications without needing to call persist() again."} | верно | Dirty checking сравнивает снимки свойств; persist нужен только новым/отсоединённым объектам. |
T14-L8 0.44 c | Doctrine | remove() executes the SQL DELETE immediately, without waiting for flush(). | «no» Пояснение: The remove() method only schedules the entity for deletion in the UnitOfWork, and the actual SQL DELETE is executed during the flush() operation.
Raw{"answer": "no", "explanation": "The remove() method only schedules the entity for deletion in the UnitOfWork, and the actual SQL DELETE is executed during the flush() operation."} | верно | remove() планирует удаление в Unit of Work; DELETE выполняется на flush() (docs — Deleting Objects). |
T15-L1 0.35 c | PostgreSQL | PostgreSQL uses MVCC, therefore readers block writers and writers block readers. | «no» Пояснение: PostgreSQL's MVCC allows readers and writers to operate concurrently without blocking each other, as readers see a snapshot of the data and writers do not block reads.
Raw{"answer": "no", "explanation": "PostgreSQL's MVCC allows readers and writers to operate concurrently without blocking each other, as readers see a snapshot of the data and writers do not block reads."} | верно | Наоборот: благодаря MVCC читатели не блокируют писателей и наоборот (снимки строк); docs PostgreSQL — Concurrency Control. |
T15-L2 0.31 c | PostgreSQL | Which SQL command shows a query's execution plan without executing the query? | «explain» Пояснение: The EXPLAIN command displays how MySQL executes a statement without running it.
Raw{"answer": "EXPLAIN", "explanation": "The EXPLAIN command displays how MySQL executes a statement without running it."} | верно | EXPLAIN без ANALYZE только строит план; проверено на PostgreSQL 17.7. |
T15-L3 0.49 c | PostgreSQL | SERIAL and GENERATED ... AS IDENTITY are just two names for the same mechanism. | «yes» Пояснение: In PostgreSQL, SERIAL is implemented using an identity column (GENERATED ... AS IDENTITY) under the hood, so they refer to the same underlying automatic ID generation mechanism.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "In PostgreSQL, SERIAL is implemented using an identity column (GENERATED ... AS IDENTITY) under the hood, so they refer to the same underlying automatic ID generation mechanism." ⏎ } | неверно верный: «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 in PostgreSQL, a UNIQUE constraint treats NULL values as distinct, allowing multiple rows with NULL in that column.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "By default in PostgreSQL, a UNIQUE constraint treats NULL values as distinct, allowing multiple rows with NULL in that column." ⏎ } ⏎ ``` | верно | Наоборот: NULLS DISTINCT по умолчанию — несколько NULL допустимы; NULLS NOT DISTINCT — опция с PG 15. Проверено на PG 17.7. |
T15-L5 0.21 c | PostgreSQL | Which PostgreSQL aggregate function concatenates strings with a separator? | «string_agg» Пояснение: The PostgreSQL aggregate function string_agg concatenates strings with a specified separator.
Raw{"answer": "string_agg", "explanation": "The PostgreSQL aggregate function string_agg concatenates strings with a specified separator."} | верно | string_agg(значение, разделитель); проверено на PostgreSQL 17.7. |
T15-L6 0.33 c | PostgreSQL | Plain VACUUM returns the space occupied by dead tuples to the operating system. | «no» Пояснение: Plain VACUUM reclaims space for internal reuse but does not return it to the operating system; only VACUUM FULL does.
Raw```json ⏎ {"answer": "no", "explanation": "Plain VACUUM reclaims space for internal reuse but does not return it to the operating system; only VACUUM FULL does."} ⏎ ``` | верно | VACUUM помечает место для переиспользования внутри таблицы; ОС его возвращает только VACUUM FULL (с эксклюзивной блокировкой). |
T15-L7 0.33 c | PostgreSQL | Which keyword in a window function definition partitions rows into groups the function is computed over? | «partition by» Пояснение: In SQL window functions, the PARTITION BY clause is used to divide the result set into partitions that the window function operates on.
Raw{"answer": "PARTITION BY", "explanation": "In SQL window functions, the PARTITION BY clause is used to divide the result set into partitions that the window function operates on."} | верно | OVER (PARTITION BY ...); проверено на PostgreSQL 17.7. |
T15-L8 0.41 c | PostgreSQL | The READ COMMITTED isolation level protects against non-repeatable reads. | «no» Пояснение: The READ COMMITTED isolation level protects against dirty reads but does not protect against non-repeatable reads, which are prevented by the REPEATABLE READ or SERIALIZABLE levels.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "The READ COMMITTED isolation level protects against dirty reads but does not protect against non-repeatable reads, which are prevented by the REPEATABLE READ or SERIALIZABLE levels." ⏎ } | верно | READ COMMITTED допускает неповторяющееся чтение; защищает REPEATABLE READ. Проверено: SHOW transaction_isolation → read committed. |
T17-L1 0.39 c | PostgreSQL: transactions and indexes | By default, PostgreSQL wraps each single SQL statement in its own implicit transaction (autocommit). | «yes» Пояснение: In PostgreSQL, by default, each single SQL statement is executed in its own implicit transaction, which is automatically committed or rolled back based on success or failure (autocommit mode).
Raw```json ⏎ {"answer": "yes", "explanation": "In PostgreSQL, by default, each single SQL statement is executed in its own implicit transaction, which is automatically committed or rolled back based on success or failure (autocommit mode)."} ⏎ ``` | верно | Без BEGIN каждый оператор коммитится сам; docs PostgreSQL — Transactions. Проверено на PG 17. |
T17-L2 0.33 c | PostgreSQL: transactions and indexes | Which SQL command ends a transaction, committing all its changes? | «commit» Пояснение: The SQL command COMMIT is used to save all changes made during the current transaction.
Raw{"answer": "COMMIT", "explanation": "The SQL command COMMIT is used to save all changes made during the current transaction."} | верно | COMMIT (END — синоним). Проверено на PG 17. |
T17-L3 0.41 c | PostgreSQL: transactions and indexes | Indexes speed up more than SELECT: UPDATE and DELETE with a search on an indexed column benefit too. | «yes» Пояснение: Database indexes are used by the query optimizer to accelerate UPDATE, DELETE, and INSERT operations by helping locate rows more efficiently, in addition to SELECT.
Raw{"answer": "yes", "explanation": "Database indexes are used by the query optimizer to accelerate UPDATE, DELETE, and INSERT operations by helping locate rows more efficiently, in addition to SELECT."} | верно | Поиск строк для изменения идёт по индексу; docs PostgreSQL — Indexes. |
T17-L4 0.45 c | PostgreSQL: transactions and indexes | To roll back part of the statements inside a transaction, PostgreSQL uses SAVEPOINT. | «yes» Пояснение: In PostgreSQL (and PHP's PDO/PGSQL implementations), SAVEPOINT allows you to mark a point in a transaction that can be rolled back to without aborting the entire transaction.
Raw{"answer": "yes", "explanation": "In PostgreSQL (and PHP's PDO/PGSQL implementations), SAVEPOINT allows you to mark a point in a transaction that can be rolled back to without aborting the entire transaction."} | верно | SAVEPOINT name; ROLLBACK TO name — частичный откат без отмены всей транзакции. Проверено на PG 17. |
T17-L5 0.29 c | PostgreSQL: transactions and indexes | EXPLAIN ANALYZE shows the query plan without executing the query. | «no» Пояснение: EXPLAIN ANALYZE actually executes the query to provide real execution times and row counts.
Raw{"answer": "no", "explanation": "EXPLAIN ANALYZE actually executes the query to provide real execution times and row counts."} | верно | Наоборот: ANALYZE реально выполняет запрос (с побочными эффектами!) и показывает фактические времена узлов; план без выполнения — plain EXPLAIN. |
T17-L6 0.25 c | PostgreSQL: transactions and indexes | Which PostgreSQL extension adds vector types and indexes for embedding search? | «pgvector» Пояснение: pgvector is a PostgreSQL extension that adds support for vector similarity search.
Raw{"answer": "pgvector", "explanation": "pgvector is a PostgreSQL extension that adds support for vector similarity search."} | верно | CREATE EXTENSION vector (проект pgvector; в проекте образ pgvector/pgvector:pg17). |
T17-L7 0.45 c | PostgreSQL: transactions and indexes | A partial index (CREATE INDEX ... WHERE ...) is built only over rows satisfying the condition. | «no» Пояснение: PHP is an interpreted scripting language and does not natively support partial indexes (a feature of databases like PostgreSQL); partial indexes are created at the database level, not via PHP itself.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "PHP is an interpreted scripting language and does not natively support partial indexes (a feature of databases like PostgreSQL); partial indexes are created at the database level, not via PHP itself." ⏎ } | неверно верный: «yes» | docs PostgreSQL — Partial Indexes; типичный кейс — индекс по «активным» записям. |
T17-L8 0.4 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 uses Serializable Snapshot Isolation (SSI) rather than row-level locking.
Raw```json ⏎ { ⏎ "answer": "no", ⏎ "explanation": "PostgreSQL's SERIALIZABLE isolation level uses Serializable Snapshot Isolation (SSI) rather than row-level locking." ⏎ } ⏎ ``` | верно | SSI (Serializable Snapshot Isolation): предикатные блокировки на снимках, не блокировки прочитанных строк; docs PostgreSQL. |
T19-L1 0.37 c | HTTP and REST API | HTTP status 201 means the request resulted in a new resource being created. | «yes» Пояснение: HTTP 201 (Created) status code is returned when a new resource has been successfully created as a result of the request.
Raw```json ⏎ { ⏎ "answer": "yes", ⏎ "explanation": "HTTP 201 (Created) status code is returned when a new resource has been successfully created as a result of the request." ⏎ } ⏎ ``` | верно | 201 Created; обычно на POST, часто с Location; RFC 9110. |
T19-L2 0.25 c | HTTP and REST API | Which HTTP status means a successful request with an empty response body (e.g. after DELETE)? | «204» Пояснение: HTTP 204 No Content indicates a successful request with no response body.
Raw{"answer": "204", "explanation": "HTTP 204 No Content indicates a successful request with no response body."} | верно | 204 No Content; RFC 9110. |
T19-L3 0.88 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. | «no» Пояснение: While the HTTP specification defines DELETE as idempotent in theory, in practice it is not guaranteed to be idempotent because it is not possible to distinguish between a request to delete a resource and a request to delete a resource that does not exist, and implementations may treat repeated deletes differently (e.g., returning 204 or 202 on first, then 404 on subsequent, which changes the response outcome).
Raw{"answer": "no", "explanation": "While the HTTP specification defines DELETE as idempotent in theory, in practice it is not guaranteed to be idempotent because it is not possible to distinguish between a request to delete a resource and a request to delete a resource that does not exist, and implementations may treat repeated deletes differently (e.g., returning 204 or 202 on first, then 404 on subsequent, which changes the response outcome)."} | неверно верный: «yes» | RFC 9110: DELETE идемпотентен (как PUT); идемпотентность ≠ безопасность — ресурс удаляется при первом вызове. |
T19-L4 0.3 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 origins are permitted to access the resource.
Raw{"answer": "no", "explanation": "The Access-Control-Allow-Origin header is sent by the server, not the client, to indicate which origins are permitted to access the resource."} | верно | Наоборот: заголовок шлёт СЕРВЕР в ответе, разрешая браузеру cross-origin запрос (CORS); в проекте nelmio/cors-bundle. |
T19-L5 0.45 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 defined in RFC 6585 as 'Too Many Requests' and is used when a client has sent too many requests in a given amount of time.
Raw{"answer": "yes", "explanation": "HTTP status code 429 is defined in RFC 6585 as 'Too Many Requests' and is used when a client has sent too many requests in a given amount of time."} | верно | 429 (+ Retry-After); RFC 6585. В проекте symfony/rate-limiter. |
T19-L6 0.26 c | HTTP and REST API | 5xx codes mean a client error, while 4xx means a server-side error. | «no» Пояснение: HTTP 4xx codes indicate client errors, while 5xx codes indicate server errors.
Raw{"answer": "no", "explanation": "HTTP 4xx codes indicate client errors, while 5xx codes indicate server errors."} | верно | Наоборот: 4xx — ошибка клиента (400, 404), 5xx — сервера (500, 503); классы статусов RFC 9110. |
T19-L7 0.33 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 specifies the media type (MIME type) of the resource or the body of the request/response.
Raw{"answer": "Content-Type", "explanation": "The Content-Type header field specifies the media type (MIME type) of the resource or the body of the request/response."} | верно | Content-Type: application/json и т.п. |
T19-L8 0.29 c | HTTP and REST API | PATCH is not required to be idempotent per RFC 5789, unlike PUT. | «yes» Пояснение: RFC 5789 explicitly states that while PUT is idempotent, PATCH is not required to be idempotent.
Raw{"answer": "yes", "explanation": "RFC 5789 explicitly states that while PUT is idempotent, PATCH is not required to be idempotent."} | верно | RFC 5789 прямо оговаривает: PATCH не гарантированно идемпотентен; PUT идемпотентен. |
T20-L1 0.52 c | Security and OAuth | Checking a password by comparing its hash to the stored hash with a plain == is sufficient. | «no» Пояснение: Using `==` can lead to type juggling vulnerabilities (e.g., '0e123' == '0e456' evaluates to true), so `===` or `hash_equals()` should be used for strict, timing-safe comparison.
Raw{"answer": "no", "explanation": "Using `==` can lead to type juggling vulnerabilities (e.g., '0e123' == '0e456' evaluates to true), so `===` or `hash_equals()` should be used for strict, timing-safe comparison."} | верно | Нужна постоянновременная проверка (password_verify) — timing-атаки; соль и алгоритм уже внутри хеша. |
T20-L2 0.4 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 typically server-generated, session-bound, and verified server-side to ensure the request originated from the authenticated user.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "CSRF tokens are typically server-generated, session-bound, and verified server-side to ensure the request originated from the authenticated user." ⏎ } | верно | symfony/security-csrf в проекте; защита от подделки межсайтовой формы. |
T20-L3 0.52 c | Security and OAuth | Which HTTP header enables the CSP (Content Security Policy) policy? | «content-security-policy» Пояснение: The Content-Security-Policy header is used by developers to mitigate common types of attacks, including Cross-Site Scripting (XSS) and data injection attacks, by declaring trusted sources of content execution.
Raw{"answer": "Content-Security-Policy", "explanation": "The Content-Security-Policy header is used by developers to mitigate common types of attacks, including Cross-Site Scripting (XSS) and data injection attacks, by declaring trusted sources of content execution."} | верно | Content-Security-Policy; белые списки источников скриптов/стилей против XSS. |
T20-L4 0.51 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 strictly an authentication protocol, and access tokens are opaque tokens used to grant access to resources rather than to identify the user (which is typically done via ID tokens in the OpenID Connect extension).
Raw{"answer": "no", "explanation": "OAuth 2.0 is an authorization framework, not strictly an authentication protocol, and access tokens are opaque tokens used to grant access to resources rather than to identify the user (which is typically done via ID tokens in the OpenID Connect extension)."} | верно | OAuth 2.0 — авторизация/делегирование доступа; аутентификацию добавляет OpenID Connect. В проекте knpuniversity/oauth2-client-bundle (yandex/github/google). |
T20-L5 0.52 c | Security and OAuth | XSS is prevented by validating input on the server before writing it to the database. | «no» Пояснение: Server-side input validation helps prevent XSS, but it is not the sole method; output encoding when data is rendered is also critical to prevent XSS.
Raw{"answer": "no", "explanation": "Server-side input validation helps prevent XSS, but it is not the sole method; output encoding when data is rendered is also critical to prevent XSS."} | верно | XSS лечится контекстным экранированием НА ВЫВОДЕ (Twig autoescape, CSP); валидация ввода не покрывает все контексты вывода. |
T20-L6 0.41 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 agent back to the client with an authorization code parameter, which is then exchanged for an access token.
Raw{"answer": "code", "explanation": "In the OAuth 2.0 authorization code flow, the authorization server redirects the user agent back to the client with an authorization code parameter, which is then exchanged for an access token."} | верно | Параметр code; обмен на токен POST-ом на /token с client_secret. |
T20-L7 0.36 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 to have a longer expiration time than access tokens and are used to fetch new access tokens without requiring the user to re-authenticate.
Raw{ ⏎ "answer": "yes", ⏎ "explanation": "Refresh tokens are designed to have a longer expiration time than access tokens and are used to fetch new access tokens without requiring the user to re-authenticate." ⏎ } | верно | Стандартная схема OAuth/OIDC: короткий access + длинный refresh. |
T20-L8 0.32 c | Security and OAuth | A password salt must be kept secret: without it the hash cannot be verified. | «no» Пояснение: A salt is typically stored alongside the hash and does not need to be secret; it just needs to be unique to prevent rainbow table attacks.
Raw{"answer": "no", "explanation": "A salt is typically stored alongside the hash and does not need to be secret; it just needs to be unique to prevent rainbow table attacks."} | верно | Соль хранится открыто (password_hash включает её в строку хеша); секретность соли не нужна. |
T18-L1 0.36 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 for proper execution and access to assertion methods.
Raw{"answer": "no", "explanation": "PHPUnit requires test classes to extend PHPUnit\\Framework\\TestCase for proper execution and access to assertion methods."} | верно | Тестом считается метод класса, наследующего TestCase (PHPUnit 10). |
T18-L2 0.27 c | Testing: PHPUnit | In PHPUnit, setUp() runs once before all tests of the class. | «no» Пояснение: setUp() runs before each test method, while setUpBeforeClass() runs once before all tests in the class.
Raw{"answer": "no", "explanation": "setUp() runs before each test method, while setUpBeforeClass() runs once before all tests in the class."} | верно | setUp() — перед КАЖДЫМ тестом; один раз на класс — setUpBeforeClass(). Проверено живым счётчиком на PHPUnit 10.5. |
T18-L3 0.29 c | Testing: PHPUnit | A data provider lets a test run with exactly one set of arguments. | «no» Пояснение: Data providers can return multiple sets of arguments to run the same test case with different inputs.
Raw{ ⏎ "answer": "no", ⏎ "explanation": "Data providers can return multiple sets of arguments to run the same test case with different inputs." ⏎ } | верно | Наоборот: наборов может быть сколько угодно — тест выполняется по разу на каждый. Проверено на 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 in PHPUnit is used to assert that a specific exception class is thrown during a test.
Raw{"answer": "expectException", "explanation": "The expectException method in PHPUnit is used to assert that a specific exception class is thrown during a test."} | верно | $this->expectException(\LogicException::class); проверено на PHPUnit 10.5. |
T18-L5 0.3 c | Testing: PHPUnit | In PHPUnit, a stub verifies which methods were called on it, while a mock only returns data. | «no» Пояснение: The statement is reversed; mocks verify interactions while stubs return pre-defined data.
Raw{"answer": "no", "explanation": "The statement is reversed; mocks verify interactions while stubs return pre-defined data."} | верно | Наоборот: стаб подставляет данные, мок проверяет взаимодействия (createStub/createMock); docs PHPUnit — Test Doubles. |
T18-L6 0.28 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 deprecates the @dataProvider annotation in favor of the #[DataProvider] attribute.
Raw{"answer": "yes", "explanation": "PHPUnit 10 deprecates the @dataProvider annotation in favor of the #[DataProvider] attribute."} | верно | Аннотация ещё парсится в PHPUnit 10/11 (AnnotationParser в 10.5.66), удаление — в 12; атрибут — стандарт. |
T18-L7 0.31 c | Testing: PHPUnit | PHPUnit does not allow one test to depend on the result of another. | «no» Пояснение: PHPUnit allows tests to depend on the results of other tests using the 'depends' annotation or attribute.
Raw```json ⏎ {"answer": "no", "explanation": "PHPUnit allows tests to depend on the results of other tests using the 'depends' annotation or attribute."} ⏎ ``` | верно | Зависимости есть: #[Depends] — зависимый тест не запустится, еслиProducer упал. |
T18-L8 0.3 c | Testing: PHPUnit | Which PHPUnit command-line option makes tests run in random order? | «--order-by=random» Пояснение: The --order-by=random option in PHPUnit allows tests to be executed in a random sequence.
Raw{"answer": "--order-by=random", "explanation": "The --order-by=random option in PHPUnit allows tests to be executed in a random sequence."} | верно | --order-by=random (PHPUnit 9+); опция есть в --help PHPUnit 10.5 (проектная). |
T01-L9 3.03 c | Syntax and operators | What does this code output?
```php
echo intdiv(7, 2) . intdiv(-7, 2);
``` | «3-3» Пояснение: intdiv(7, 2) returns 3 and intdiv(-7, 2) returns -3, concatenated without a space.
Raw{"answer": "3-3", "explanation": "intdiv(7, 2) returns 3 and intdiv(-7, 2) returns -3, concatenated without a space."} | верно | intdiv truncates toward zero: intdiv(-7, 2) = -3, not -4. |
T01-L10 1.08 c | Syntax and operators | What does this code output?
```php
echo -3 ** 2;
``` | «9» Пояснение: In PHP, the exponentiation operator `**` has higher precedence than the unary minus, so `-3 ** 2` is interpreted as `-(3 ** 2)`, which equals -9. However, looking closer at PHP documentation and behavior, `-3 ** 2` actually evaluates to `-9` because `**` binds tighter than the unary `-`. Wait, let me double-check. In PHP, `-3 ** 2` is equivalent to `-(3**2)` = -9. But the question asks for the result. Let's re-verify: `var_dump(-3 ** 2);` outputs `int(-9)`. So the answer is -9.
Raw{"answer": 9, "explanation": "In PHP, the exponentiation operator `**` has higher precedence than the unary minus, so `-3 ** 2` is interpreted as `-(3 ** 2)`, which equals -9. However, looking closer at PHP documentation and behavior, `-3 ** 2` actually evaluates to `-9` because `**` binds tighter than the unary `-`. Wait, let me double-check. In PHP, `-3 ** 2` is equivalent to `-(3**2)` = -9. But the question asks for the result. Let's re-verify: `var_dump(-3 ** 2);` outputs `int(-9)`. So the answer is -9."} | неверно верный: «-9» | ** is right-associative and binds tighter than unary minus: -(3²). |
T02-L9 0.91 c | Types and comparisons | What does this code output?
```php
echo '1e1' == '10' ? 'true' : 'false';
``` | «true» Пояснение: In PHP, when comparing a numeric string with a non-numeric string, both are converted to integers, so '1e1' becomes 1 and '10' becomes 10, making them unequal, but the question asks what the ternary outputs; since 1 == 10 is false, it outputs 'false'. Wait, let me re-evaluate: '1e1' is a numeric string representing 10, and '10' is also 10, so they are equal in loose comparison, thus outputting 'true'.
Raw{"answer": "true", "explanation": "In PHP, when comparing a numeric string with a non-numeric string, both are converted to integers, so '1e1' becomes 1 and '10' becomes 10, making them unequal, but the question asks what the ternary outputs; since 1 == 10 is false, it outputs 'false'. Wait, let me re-evaluate: '1e1' is a numeric string representing 10, and '10' is also 10, so they are equal in loose comparison, thus outputting 'true'."} | верно | Both strings are numeric — compared as numbers: 10 == 10. |
T02-L10 0.37 c | Types and comparisons | What does this code output?
```php
switch ('a') {
case 0: echo 'zero'; break;
default: echo 'other';
}
``` | «other» Пояснение: PHP's switch statement uses loose comparison (==), but 'a' is not equal to 0, so it falls through to the default case, which echoes 'other'.
Raw{"answer": "other", "explanation": "PHP's switch statement uses loose comparison (==), but 'a' is not equal to 0, so it falls through to the default case, which echoes 'other'."} | верно | PHP 8: 'a' == 0 → false (used to be true) — default fires. |
T03-L9 0.35 c | Strings | What does this code output?
```php
echo strtr('abc', ['a' => '1', 'ab' => '2']);
``` | «2bc» Пояснение: strtr replaces the longest matching keys first, so 'ab' becomes '2' and the remaining 'c' stays, resulting in '2bc'.
Raw{"answer": "2bc", "explanation": "strtr replaces the longest matching keys first, so 'ab' becomes '2' and the remaining 'c' stays, resulting in '2bc'."} | неверно верный: «2c» | strtr with an array prefers the longest matching key. |
T03-L10 0.37 c | Strings | What does this code output?
```php
echo '[' . substr('hello', -10) . ']';
``` | «[hello]» Пояснение: When the start position in substr() is negative and its absolute value is greater than or equal to the string length, it returns the entire string from the beginning.
Raw{"answer": "[hello]", "explanation": "When the start position in substr() is negative and its absolute value is greater than or equal to the string length, it returns the entire string from the beginning."} | верно | A negative start beyond the string is clamped to the beginning. |
T04-L9 0.45 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 merges arrays, keeping keys from the left array if they exist in both, so array_keys returns ['k', 'n', 'm'].
Raw```json ⏎ {"answer": "k,n,m", "explanation": "The + operator merges arrays, keeping keys from the left array if they exist in both, so array_keys returns ['k', 'n', 'm']."} ⏎ ``` | верно | The + operator: on duplicate string keys the left array wins. |
T04-L10 0.5 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));
``` | «xyz» Пояснение: The array is sorted by the third element (index 2) using a spaceship operator, then the second elements (index 1) are concatenated into a single string.
Raw```json ⏎ { ⏎ "answer": "xyz", ⏎ "explanation": "The array is sorted by the third element (index 2) using a spaceship operator, then the second elements (index 1) are concatenated into a single string." ⏎ } ⏎ ``` | неверно верный: «yxz» | Sorts are stable since 8.0: x and z keep their order on a tie. |
T05-L10 3.43 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 expands the array by key, so f(5, 1) is called, resulting in 5 - 1 = 4.
Raw{ ⏎ "answer": 4, ⏎ "explanation": "The spread operator expands the array by key, so f(5, 1) is called, resulting in 5 - 1 = 4." ⏎ } | верно | String keys of a spread array become named arguments. |
T05-L9 0.64 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 first-class callable $f captures the object instance $p at the time of creation, so it still holds a reference to the object even after $p is set to null, allowing g() to be called and return the private property v.
Raw{"answer": 3, "explanation": "The first-class callable $f captures the object instance $p at the time of creation, so it still holds a reference to the object even after $p is set to null, allowing g() to be called and return the private property v."} | верно | First-class callable syntax binds $this at creation time. |
T06-L9 0.37 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 late static binding class name, which is 'B' since the object is an instance of B.
Raw{"answer": "B", "explanation": "The static::class keyword returns the late static binding class name, which is 'B' since the object is an instance of B."} | верно | Late static binding: static::class is the receiver's class. |
T06-L10 0.4 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 by 2, so setting $c->x = 5 results in $this->x = 10.
Raw{"answer": 10, "explanation": "The setter multiplies the assigned value by 2, so setting $c->x = 5 results in $this->x = 10."} | верно | Inside the set hook, $this->x writes the backing store (no recursion): 5*2. |
T07-L9 0.49 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' keyword prioritizes TB's f() over TA's, while 'as g' creates an alias of TA's f() as g(), resulting in 'BA'.
Raw{"answer": "BA", "explanation": "The 'insteadof' keyword prioritizes TB's f() over TA's, while 'as g' creates an alias of TA's f() as g(), resulting in 'BA'."} | верно | insteadof picks the implementation; as keeps the other under an alias. |
T07-L10 0.4 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» Пояснение: Traits do not share static properties between classes; each class that uses a trait has its own copy of the static property, so CX::$n = 1 does not affect CY::$n.
Raw{"answer": "0", "explanation": "Traits do not share static properties between classes; each class that uses a trait has its own copy of the static property, so CX::$n = 1 does not affect CY::$n."} | верно | A trait's static property is copied into each consuming class. |
T08-L10 0.44 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 try block returns a value but a finally block also returns a value, the return value from the finally block overrides the try block's return value.
Raw```json ⏎ {"answer": 2, "explanation": "In PHP, if a try block returns a value but a finally block also returns a value, the return value from the finally block overrides the try block's return value."} ⏎ ``` | верно | A return in finally overrides the return from try. |
T08-L9 0.4 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» Пояснение: The finally block executes and throws a new LogicException, replacing the original RuntimeException, which is then caught by the outer catch block and its message 'second' is printed.
Raw{"answer": "second", "explanation": "The finally block executes and throws a new LogicException, replacing the original RuntimeException, which is then caught by the outer catch block and its message 'second' is printed."} | верно | An exception from finally replaces the in-flight one — the last thrown is caught. |
T09-L9 0.39 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» Пояснение: use App\Foo as Baz makes Baz::class resolve to App\Foo, while \Baz::class resolves to the global Baz class name.
Raw{"answer": "App\\Foo|Baz", "explanation": "use App\\Foo as Baz makes Baz::class resolve to App\\Foo, while \\Baz::class resolves to the global Baz class name."} | верно | The use alias applies to unqualified names; a leading \ escapes to the global scope. |
T09-L10 0.31 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('Foo') returns false in the Ns namespace, but class_exists('Ns\Foo') returns true.
Raw{"answer": "noyes", "explanation": "class_exists('Foo') returns false in the Ns namespace, but class_exists('Ns\\Foo') returns true."} | верно | Dynamic names are not resolved against the namespace — 'Foo' is the global class. |
T10-L9 0.46 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 foreach loop iterates by reference, leaving $v referenced to the last element of the array, so setting $v to 99 modifies the last element of $a.
Raw{"answer": "1,2,99", "explanation": "The foreach loop iterates by reference, leaving $v referenced to the last element of the array, so setting $v to 99 modifies the last element of $a."} | верно | After a by-ref foreach, $v remains a reference to the last element. |
T10-L10 0.47 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();
``` | «2» Пояснение: Static variables are shared across all instances of the same class, so each call to inc() increments the shared $n, and the third call returns 2.
Raw{"answer": 2, "explanation": "Static variables are shared across all instances of the same class, so each call to inc() increments the shared $n, and the third call returns 2."} | неверно верный: «3» | A method's static variable belongs to the parent's method — subclasses share it. |
T11-L9 0.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, then when 10 is sent, $x becomes 10 and the function returns 11.
Raw{"answer": 11, "explanation": "The generator yields 1, then when 10 is sent, $x becomes 10 and the function returns 11."} | верно | send() resumes the generator: $x = 10, return 10+1. |
T11-L10 0.46 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 forwards values from inner (1, 2) and captures its return value ('ok'), which is then yielded by outer, resulting in the sequence 1, 2, ok.
Raw{"answer": "1,2,ok", "explanation": "yield from forwards values from inner (1, 2) and captures its return value ('ok'), which is then yielded by outer, resulting in the sequence 1, 2, 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 1.88 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';
``` | «nono» Пояснение: password_needs_rehash returns false (no) for both calls because the existing hash cost of 4 matches the first check's cost of 4, and it also returns false for the second check in this specific version context typically expected, but strictly speaking, cost 4 vs 5 should return true for the second. Let's re-evaluate: password_needs_rehash checks if the hash needs rehashing based on the algorithm and cost. If the hash was created with cost 4, and we ask if it needs rehashing for cost 4, it is false ('no'). If we ask if it needs rehashing for cost 5, since 4 != 5, it is true ('yes'). So the output is 'no' then 'yes' => 'noyes'. Wait, let me double check the behavior. password_needs_rehash compares the cost in the hash with the cost provided. If they differ, it returns true. 4 != 5, so true ('yes'). 4 == 4, so false ('no'). Output: 'no' + 'yes' = 'noyes'.
Raw{ ⏎ "answer": "nono", ⏎ "explanation": "password_needs_rehash returns false (no) for both calls because the existing hash cost of 4 matches the first check's cost of 4, and it also returns false for the second check in this specific version context typically expected, but strictly speaking, cost 4 vs 5 should return true for the second. Let's re-evaluate: password_needs_rehash checks if the hash needs rehashing based on the algorithm and cost. If the hash was created with cost 4, and we ask if it needs rehashing for cost 4, it is false ('no'). If we ask if it needs rehashing for cost 5, since 4 != 5, it is true ('yes'). So the output is 'no' then 'yes' => 'noyes'. Wait, let me double check the behavior. password_needs_rehash compares the cost in the hash with the cost provided. If they differ, it returns true. 4 != 5, so true ('yes'). 4 == 4, so false ('no'). Output: 'no' + 'yes' = 'noyes'." ⏎ } | неверно верный: «noyes» | password_needs_rehash compares the hash's options with the target: cost 4 = 4 → 'no', cost 5 ≠ 4 → 'yes'. |
T12-L10 0.71 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» Пояснение: In PHP 8.0, E_STRICT was deprecated and its value is 2048. On PHP 8.5, E_ALL still includes E_STRICT (or its deprecation equivalent is retained for compatibility in bitmask checks), so the bitwise AND is non-zero, resulting in 'strict-in'.
Raw{ ⏎ "answer": "strict-in", ⏎ "explanation": "In PHP 8.0, E_STRICT was deprecated and its value is 2048. On PHP 8.5, E_ALL still includes E_STRICT (or its deprecation equivalent is retained for compatibility in bitmask checks), so the bitwise AND is non-zero, resulting in 'strict-in'." ⏎ } | неверно верный: «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.45 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::create automatically maps HTTP headers from the 'HTTP_*' keys in the server bag to the headers collection.
Raw{"answer": "mapped", "explanation": "Symfony's Request::create automatically maps HTTP headers from the 'HTTP_*' keys in the server bag to the headers collection."} | верно | 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 1.71 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;
``` | «bac» Пояснение: Listeners are executed in reverse order of priority (higher first, then default, then lower), so B (priority 10) runs first, then A (priority 0), then C (priority 5) is actually before A? No: priority 10 (B), priority 5 (C), priority 0 (A) -> wait: standard behavior is higher priority first. 10, 5, 0. So B, C, A. Let me re-verify: addListener with priority 10, then 0, then 5. Sorted descending: 10, 5, 0. Output: B, C, A -> 'BCA'. Wait, the explanation in JSON should match the answer. Let me correct the thought: Higher priority executes first. 10 > 5 > 0. So order is B, C, A. The string is 'BCA'. I will update the explanation.
Raw{"answer": "BAC", "explanation": "Listeners are executed in reverse order of priority (higher first, then default, then lower), so B (priority 10) runs first, then A (priority 0), then C (priority 5) is actually before A? No: priority 10 (B), priority 5 (C), priority 0 (A) -> wait: standard behavior is higher priority first. 10, 5, 0. So B, C, A. Let me re-verify: addListener with priority 10, then 0, then 5. Sorted descending: 10, 5, 0. Output: B, C, A -> 'BCA'. Wait, the explanation in JSON should match the answer. Let me correct the thought: Higher priority executes first. 10 > 5 > 0. So order is B, C, A. The string is 'BCA'. I will update the explanation."} | неверно верный: «bca» | Listeners run by descending priority: 10 (B), 5 (C), 0 (A). |
T14-L10 0.47 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 identity map ensures that for a given primary key, the same PHP object instance is returned on subsequent find() calls within the same EntityManager unit of work.
Raw{"answer": "same", "explanation": "Doctrine ORM's identity map ensures that for a given primary key, the same PHP object instance is returned on subsequent find() calls within the same EntityManager unit of work."} | верно | Identity map: a second find for the same id returns the same instance. |
T14-L9 0.38 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» Пояснение: In Doctrine ORM, if an entity is persisted and then removed before the flush, the insert operation is never executed, leaving the table empty.
Raw{"answer": 0, "explanation": "In Doctrine ORM, if an entity is persisted and then removed before the flush, the insert operation is never executed, leaving the table empty."} | верно | The unit of work schedules INSERT at flush: remove after persist cancels it. |
T15-L10 0.36 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, so it returns 1.
Raw{"answer": "1", "explanation": "count(x) counts only non-NULL values in the column, so it returns 1."} | верно | count(column) skips NULLs; count(*) would return 2. |
T15-L9 0.54 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) computes cumulative sums (10, 30, 60) for each row in the subquery, which are then concatenated by string_agg in the order of id.
Raw{"answer": "10,30,60", "explanation": "The window function sum(x) OVER (ORDER BY id) computes cumulative sums (10, 30, 60) for each row in the subquery, which are then concatenated by string_agg in the order of id."} | верно | With ORDER BY the default window frame is running (start to current row). |
T16-L9 0.48 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» Пояснение: The MessageBus executes the middleware stack in the order they are provided, so both 'M1' and 'M2' are echoed sequentially before returning.
Raw{"answer": "M1M2", "explanation": "The MessageBus executes the middleware stack in the order they are provided, so both 'M1' and 'M2' are echoed sequentially before returning."} | верно | The first-added middleware runs first (outermost). |
T16-L10 1.79 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;
``` | «1» Пояснение: HandleMessageMiddleware processes handlers in order, and after the first handler (h1) increments $n by 1, subsequent handlers (h2) are not called because the envelope is marked as handled by default in this context, or the first handler's completion stops further processing in standard HandleMessageMiddleware behavior for a single handler unless configured otherwise, but actually, HandleMessageMiddleware iterates through ALL handlers found for the message type. Wait, let me re-evaluate: HandlersLocator returns an array of descriptors. HandleMessageMiddleware iterates through each handler descriptor. So $n += 1 (by h1) then $n += 10 (by h2). Total is 11. But wait: does HandleMessageMiddleware stop after the first handler? No, it processes all handlers in the array provided by the locator for that message class. So both handlers run. 1 + 10 = 11.
Raw```json ⏎ { ⏎ "answer": 1, ⏎ "explanation": "HandleMessageMiddleware processes handlers in order, and after the first handler (h1) increments $n by 1, subsequent handlers (h2) are not called because the envelope is marked as handled by default in this context, or the first handler's completion stops further processing in standard HandleMessageMiddleware behavior for a single handler unless configured otherwise, but actually, HandleMessageMiddleware iterates through ALL handlers found for the message type. Wait, let me re-evaluate: HandlersLocator returns an array of descriptors. HandleMessageMiddleware iterates through each handler descriptor. So $n += 1 (by h1) then $n += 10 (by h2). Total is 11. But wait: does HandleMessageMiddleware stop after the first handler? No, it processes all handlers in the array provided by the locator for that message class. So both handlers run. 1 + 10 = 11." ⏎ } ⏎ ``` | неверно верный: «11» | All registered handlers of the message run: 1 + 10 = 11. |
T17-L9 0.55 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» Пояснение: The first insert succeeds, adding one row with a=1. The second insert triggers a unique index conflict on a=1, so ON CONFLICT DO NOTHING skips it. Thus, count(*) returns 1.
Raw{"answer": 1, "explanation": "The first insert succeeds, adding one row with a=1. The second insert triggers a unique index conflict on a=1, so ON CONFLICT DO NOTHING skips it. Thus, count(*) returns 1."} | верно | ON CONFLICT DO NOTHING skips the duplicate: one insert. |
T17-L10 0.38 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» Пояснение: The UNIQUE constraint is deferred, so duplicate values are not checked until the end of the transaction, allowing both inserts to succeed.
Raw{"answer": 2, "explanation": "The UNIQUE constraint is deferred, so duplicate values are not checked until the end of the transaction, allowing both inserts to succeed."} | верно | DEFERRED postpones the uniqueness check to COMMIT — count sees 2 rows. |
T18-L9 2.09 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) | «2» Пояснение: The --filter test_sum matches only the test_sum method (not test_sum_abs), and since it has a data provider with 3 entries, one might think 3. But actually, PHPUnit's --filter matches test names case-insensitively by regex pattern. test_sum matches test_sum and test_sum_abs (since test_sum is a substring/prefix). So both test_sum (3 tests) and test_sum_abs (3 tests) would match → 6 tests total. Wait, let me reconsider: In PHPUnit, --filter uses a regex pattern that matches against the test method name (and possibly the class). The pattern 'test_sum' would match both 'test_sum' and 'test_sum_abs' because it's a substring match (unless anchored). Therefore, test_sum runs 3 times (from data provider) and test_sum_abs runs 3 times (from data provider), totaling 6. But let me verify: Actually, PHPUnit --filter by default matches if the pattern is found in the test name, so 'test_sum' is a substring of 'test_sum_abs'. So yes, both methods are included. Each has 3 data set entries. Total = 3 + 3 = 6.
Raw{"answer": 2, "explanation": "The --filter test_sum matches only the test_sum method (not test_sum_abs), and since it has a data provider with 3 entries, one might think 3. But actually, PHPUnit's --filter matches test names case-insensitively by regex pattern. test_sum matches test_sum and test_sum_abs (since test_sum is a substring/prefix). So both test_sum (3 tests) and test_sum_abs (3 tests) would match → 6 tests total. Wait, let me reconsider: In PHPUnit, --filter uses a regex pattern that matches against the test method name (and possibly the class). The pattern 'test_sum' would match both 'test_sum' and 'test_sum_abs' because it's a substring match (unless anchored). Therefore, test_sum runs 3 times (from data provider) and test_sum_abs runs 3 times (from data provider), totaling 6. But let me verify: Actually, PHPUnit --filter by default matches if the pattern is found in the test name, so 'test_sum' is a substring of 'test_sum_abs'. So yes, both methods are included. Each has 3 data set entries. Total = 3 + 3 = 6."} | неверно верный: «6» | --filter is a substring match: test_sum also matches test_sum_abs (3+3 datasets). |
T18-L10 0.58 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 DataProvider 'prov' yields two arrays ([1] and [-1]), so two test cases are run. test_x asserts $x > 0; the first case (1) passes, the second (-1) fails, resulting in 1 failure.
Raw{"answer": "2,1", "explanation": "The DataProvider 'prov' yields two arrays ([1] and [-1]), so two test cases are run. test_x asserts $x > 0; the first case (1) passes, the second (-1) fails, resulting in 1 failure."} | верно | 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 explicitly sets the HTTP request method to POST.
Raw{"answer": "POST", "explanation": "The -d flag in curl explicitly sets the HTTP request method to POST."} | верно | -d/-F switches curl to POST by default. |
T19-L10 0.36 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 instructs it to use the GET method and place the data in the URL query string.
Raw```json ⏎ {"answer": "GET", "explanation": "The -G flag in curl instructs it to use the GET method and place the data in the URL query string."} ⏎ ``` | верно | -G turns -d data into the query string; the method stays GET. |
T20-L9 0.5 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» Пояснение: Per RFC 6749 Section 5.2, if the client authentication fails (including a non-existent client_id), the authorization server MUST return the error code 'invalid_client'.
Raw{ ⏎ "answer": "invalid_client", ⏎ "explanation": "Per RFC 6749 Section 5.2, if the client authentication fails (including a non-existent client_id), the authorization server MUST return the error code 'invalid_client'." ⏎ } | верно | Unknown client → invalid_client (RFC 6749 §5.2). |
T20-L10 0.41 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 flow, the access token is returned in the URI fragment identifier to prevent it from being sent in server logs.
Raw{"answer": "fragment", "explanation": "In the implicit grant flow, the access token is returned in the URI fragment identifier to prevent it from being sent in server logs."} | верно | The implicit flow passes the token in the URL fragment (#) — it never reaches the server. |
T21-L9 0.62 c | Twig | What does this Twig template output?
```twig
{{ false|default(2) * 3 }}
``` | «2» Пояснение: In Twig, the 'default' filter checks if the value is null or undefined. Since 'false' is not null, the 'default' filter returns 'false' itself. Then, 'false' is coerced to the integer 0 in the multiplication operation, so 0 * 3 equals 0.
Raw{"answer": 2, "explanation": "In Twig, the 'default' filter checks if the value is null or undefined. Since 'false' is not null, the 'default' filter returns 'false' itself. Then, 'false' is coerced to the integer 0 in the multiplication operation, so 0 * 3 equals 0."} | неверно верный: «6» | default replaces exactly false/null/''/[] — false becomes 2, 2*3 = 6; the naive 'default is for undefined only' yields 0. |
T21-L10 0.49 c | Twig | What exception class does render() of this template throw?
```twig
{{ 'a' ~ 1 + 2 }}
``` | «string» Пояснение: In Twig, the concatenation operator ~ has lower precedence than arithmetic operators like +, so 'a' ~ (1 + 2) is evaluated as 'a' ~ 3, which results in the string 'a3'.
Raw{"answer": "string", "explanation": "In Twig, the concatenation operator ~ has lower precedence than arithmetic operators like +, so 'a' ~ (1 + 2) is evaluated as 'a' ~ 3, which results in the string 'a3'."} | неверно верный: «runtimeerror» | In Twig ~ binds tighter than +: ('a' ~ 1) + 2 → string + int → a render error (RuntimeError). |
T22-L9 0.32 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 validation violation.
Raw{"answer": "1", "explanation": "The array contains an empty string which violates the NotBlank constraint, resulting in one validation violation."} | неверно верный: «0» | NotBlank treats null, '', [] as blank — the array [''] is not blank. |
T22-L10 0.33 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);
}
``` | «valid» Пояснение: A Symfony form of type TextType with no data or constraints is considered valid by default.
Raw{"answer": "valid", "explanation": "A Symfony form of type TextType with no data or constraints is considered valid by default."} | неверно верный: «symfony\component\form\exception\logicexception» | isValid() on a non-submitted form throws LogicException, it does not return false. |
T23-L9 0.42 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 and returns the same instance for a public service on multiple get() calls within the same container instance.
Raw{"answer": "same", "explanation": "The Symfony DI container caches and returns the same instance for a public service on multiple get() calls within the same container instance."} | верно | Container services are shared: two get() calls yield one instance. |
T23-L10 0.49 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!» Пояснение: The container compiles and resolves nested parameter placeholders, substituting '%name%' in '%greeting%' and then '%greeting%' in '%message%', resulting in 'hi Bob!'.
Raw{"answer": "hi Bob!", "explanation": "The container compiles and resolves nested parameter placeholders, substituting '%name%' in '%greeting%' and then '%greeting%' in '%message%', resulting in 'hi Bob!'."} | верно | compile() resolves %-references transitively: %greeting% → 'hi %name%' → 'hi Bob!', the answer assembles over two hops. |
T24-L9 1.53 c | Bootstrap | What is the max-width of .container in Bootstrap 5.3 at a 992px viewport? | «720px» Пояснение: In Bootstrap 5.3, the max-width for the 'md' breakpoint (576px - 767.98px is sm, 768px - 991.98px is md) at a 992px viewport (which is the start of the 'lg' breakpoint) actually uses the 'md' container definition for screens below 992px, but at exactly 992px it switches to 'lg'. Wait, standard Bootstrap 5 max-widths are: sm 540px, md 720px, lg 960px, xl 1140px, xxl 1320px. At a 992px viewport, the media query for 'lg' (min-width: 992px) is active. Therefore, the container width is 960px.
Raw{"answer": "720px", "explanation": "In Bootstrap 5.3, the max-width for the 'md' breakpoint (576px - 767.98px is sm, 768px - 991.98px is md) at a 992px viewport (which is the start of the 'lg' breakpoint) actually uses the 'md' container definition for screens below 992px, but at exactly 992px it switches to 'lg'. Wait, standard Bootstrap 5 max-widths are: sm 540px, md 720px, lg 960px, xl 1140px, xxl 1320px. At a 992px viewport, the media query for 'lg' (min-width: 992px) is active. Therefore, the container width is 960px."} | неверно верный: «960» | 5.x container widths: 540/720/960/1140/1320 (sm–xxl); 992 → 960px. |
T24-L10 0.67 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-danger» Пояснение: In CSS, when two classes of the same specificity target the same property, the last one defined in the stylesheet takes precedence. In Bootstrap, .text-primary is defined after .text-danger in the CSS, so text-primary actually wins for the color property, not text-danger.
Raw{"answer": "text-danger", "explanation": "In CSS, when two classes of the same specificity target the same property, the last one defined in the stylesheet takes precedence. In Bootstrap, .text-primary is defined after .text-danger in the CSS, so text-primary actually wins for the color property, not text-danger."} | верно | Specificity ties — the later rule wins: text-danger is declared after text-primary. |
T25-L9 0.53 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 the Domain layer. According to the rules, Domain can only depend on Domain. It depends on App\Application\PlaceOrder (Application layer) and App\Infrastructure\Db (Infrastructure layer), resulting in two violations.
Raw{"answer": 2, "explanation": "The class is in the Domain layer. According to the rules, Domain can only depend on Domain. It depends on App\\Application\\PlaceOrder (Application layer) and App\\Infrastructure\\Db (Infrastructure layer), resulting in two violations."} | верно | Domain may depend only on Domain: PlaceOrder (Application) + Db (Infrastructure) = 2. |
T25-L10 0.6 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,
) {}
}
``` | «2» Пояснение: The Domain layer is only allowed to depend on Domain, so the imports of App\Application\PlaceOrder and App\Infrastructure\Db are violations (the fully qualified name in the constructor is not a separate import/use statement violation).
Raw{"answer": 2, "explanation": "The Domain layer is only allowed to depend on Domain, so the imports of App\\Application\\PlaceOrder and App\\Infrastructure\\Db are violations (the fully qualified name in the constructor is not a separate import/use statement violation)."} | неверно верный: «3» | The inline FQCN \App\Infrastructure\Logger counts too: Application + Db + Logger = 3. |
T26-L10 0.51 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 code creates a Money object with amount 10, then adds 5 to create a new Money object with amount 15; it then echoes the original amount and the new amount separated by a comma.
Raw{"answer": "10,15", "explanation": "The code creates a Money object with amount 10, then adds 5 to create a new Money object with amount 15; it then echoes the original amount and the new amount separated by a comma."} | верно | The VO is immutable: add() returns a new instance; the original is unchanged. |
T26-L9 0.37 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 remove method throws an exception before unsetting the item when count is 1, so the item remains in the array.
Raw{"answer": 1, "explanation": "The remove method throws an exception before unsetting the item when count is 1, 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.28 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 instantiates class C and calls its hi() method, which returns the string 'hi'.
Raw{"answer": "hi", "explanation": "The code instantiates 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.35 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» Пояснение: Initially, the object is uninitialized, so the first check prints 'yes'. Accessing $o->v triggers the lazy initializer, setting $v to 21 and marking the object as initialized, so the second check prints 'no'.
Raw{"answer": "yesno", "explanation": "Initially, the object is uninitialized, so the first check prints 'yes'. Accessing $o->v triggers the lazy initializer, setting $v to 21 and marking the object as initialized, so the second check prints 'no'."} | верно | newLazyGhost (8.4): the object stays lazy until first access — reading a property initializes it and clears the flag. |
T28-L9 0.38 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 AbstractGuardAuthenticator class was removed in Symfony 8 (deprecated in 5.3, removed in 8.0).
Raw{"answer": "no", "explanation": "The AbstractGuardAuthenticator class was removed in Symfony 8 (deprecated in 5.3, removed in 8.0)."} | верно | Guard authentication was removed in Symfony 7.0 — the class is gone in 8.1. |
T28-L10 0.53 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';
``` | «yesno» Пояснение: In Symfony 8.1, AnnotationClassLoader was removed (deprecated in 6.4), so its existence check returns false ('no'), while AttributeClassLoader exists, returning true ('yes'); concatenating these gives 'yesno'.
Raw{"answer": "yesno", "explanation": "In Symfony 8.1, AnnotationClassLoader was removed (deprecated in 6.4), so its existence check returns false ('no'), while AttributeClassLoader exists, returning true ('yes'); concatenating these gives 'yesno'."} | неверно верный: «noyes» | Annotation loaders were removed in 7.0; only attribute loaders remain (Annotation→Attribute). |