Friday's PHP quiz: some Brad programmer's adventures, one weird sequence and prizes

    Hello! They promised - we do: we continue the series of mini-quizzes devoted to different programming languages ​​in our blog (previous: 1 (in Python, PHP, Golang and DevOps) , 2 (completely Go) ). Today's edition is dedicated to PHP.

    Under the cut - eight questions, some adventures of the programmer Brad, one strange sequence and cool merchandise as prizes. Quiz runs until July 4.

    UPD 2: As agreed, we post the quiz quiz analysis. Explanations hid under the spoiler after the correct answers. If you have any questions, ask them in the comments.

    UPD: We've finished accepting answers. Thanks to everyone who participated! We are preparing an analysis of tasks. The answers to them are inside the text, and the winners and prize-winners under the spoiler.
    Winners and prize-winners of the PHP quiz

    Победитель


    egor_nullptr

    Призеры


    Мы случайным образом выбрали десять лучших участников, допустивших не больше двух ошибок в ответах: Dimd13, slimus, alexchromets, Donquih0te, TexElless, SamDark, AdmAlexus, voiceofnoise, Raz-Mik, Serj_By.

    Запись розыгрыша


    Бонус!


    Тем, кто допустил всего одну ошибку, мы дополнительно дарим холиварные кости, с которыми можно решить на каком бэкенд-языке и фронтенд-фреймворке писать ваш новый проект/или переделать старый. Их получают: DjSebas, TexElless, Turik-us, offlinewan, voiceofnoise, andrey_96, delight-almighty.




    Rules of the game


    To the first person who answers them correctly, we’ll send Avito's souvenir pack: a php-elephant T-shirt, socks and holivary bones (you can tell in what backend language and front-end framework your new project will be written).

    We will send Avito-socks to ten others who answer correctly . Let's play using randomizer. He will determine who will go to two more T-shirts and a set of bones.



    Questions and answer choices


    Question 1


    What will output code:

    <?php
    $a = [1, 2, 3];
    foreach($a as &$value) {}
    foreach($a as $value) {}
    print_r($a);
    

    Variants of answers:

    1. Array (1, 2, 3)
    2. Array (1, 2, 2)
    3. Array (3, 2, 1)
    4. Mistake

    Correct answer
    Array(1, 2, 2)

    Explanation
    Поскольку в php переменные созданные в цикле остаются жить после его завершения, к началу второго цикла переменная $value — это ссылка на последний элемент массива. Во время итерации последнего foreach значения из массива записываются в его последний элемент (т.к. $value — это ссылка). Так будет выглядеть массив на каждой итерации второго цикла:
    1. [1, 2, 1]
    2. [1, 2, 2]
    3. [1, 2, 2]

    Question 2


    What will output code:

    <?phpfunctionsowCrops(){ return'wheat'; }
    functionmillWheat(){ return'flour'; }
    functionbake($flour){ return'cupcake'; }
    functiongenerator(){
        $flour = yield millWheat();
        $wheat = yield sowCrops();
        return bake($flour);
    };
    $gen = generator();
    foreach ($gen as $key => $value) {
        echo $key . ' => ' . $value . PHP_EOL;
    }
    echo $gen->getReturn();
    

    Variants of answers:

    1. 0 => flour
       1 => wheat
      

    2. 0 => wheat
       1 => flour
       2 => cupcake
      

    3. 0 => flour
      1 => wheat
      cupcake 
      

    4. cupcake



    Correct answer
    4.
    0 => flour
    1 => wheat
    cupcake 
    



    Explanation
    No comments. Просто немного мудрёный пример с генераторами.

    Question 3


    One day, Brad, a programmer, decided to port one library from Go to PHP to collect stars on GitHub and wondered:

    Is the following construct possible?

    <?php 
    print_r(...(new Foo()));

    Variants of answers:

    1. Yes, the Foo class must implement the Traversable interface.
    2. Yes, the Foo class must implement the ArrayAccess interface methods.
    3. No, there will be an error, the argument of the ...- operator must be an array

    Correct answer
    1. Да, класс Foo должен реализовать интерфейс Traversable

    Explanation
    Тут всё просто. Из документации Argument Unpacking:
    Массивы и объекты, реализующие интерфейс Traversable могут быть распакованы в список аргументов при передаче в функцию с помощью оператора ...


    Question 4


    What sorting algorithm is used in the heart of PHP for functions such as sort, etc.?

    Variants of answers:

    1. non-recursive mergesort
    2. heapsort (Edsger Dijkstra's smoothsort variation)
    3. quicksort median of three
    4. introsort

    Correct answer
    4. introsort

    Explanation
    Используется introsort. Исходный код можно посмотреть на Гитхабе. В документации есть упоминание об использовании quicksort, но тут нет противоречия, ведь introsort — гибридный алгоритм сортировки, где при малом количестве элементов используется сортировка вставкой, а позже используется более быстрый алгоритм: quicksort или heapsort.


    Question 5


    There is a code:

    <?phpclassFactory{
        publicfunctiongetLambda(): Closure{
            returnfunction(){
                printf("Here I am (%s)!\n", get_class($this));
            };
        }
        publicfunctiongetLambda2(): Closure{
            returnstaticfunction(){
                printf("Here I am (%s)!\n", get_class($this));
            };
        }
    }
    

    Question: Is there a difference between the return values ​​of getLambda and getLambda2?

    Variants of answers:

    1. In one case, the keyword static :) is used, but it does not affect
    2. The result of getLambda2 () cannot be bound to any object.
    3. So you can not write: there will be a syntax error "Syntax error: static keyword used in wrong context"
    4. The closure of getLamda2 () can bind (bindTo) only to classes

    Correct answer
    2. Результат getLambda2() нельзя привязать к какому-нибудь объекту

    Explanation
    Метод getLambda2() возвращает статическую анонимную функцию, которую нельзя привязать к объекту через ->bindTo() метод. Их использование редко встречается в коде, но всё же

    Question 6


    What will output code:

    <?php
    $a = true;
    $b = false;
    $c = $a and $b;
    $d = $a && $b;
    var_dump($c);
    var_dump($d);
    

    Variants of answers:

    1. bool(false)
      bool(false)
      
    2. bool(false)
      bool(true)
      
    3. bool(true)
      bool(true)
      
    4. bool(true)
      bool(false)
      

    Correct answer
    4.
    bool(true)
    bool(false)
    


    Explanation
    Разница между && и and в приоритете. Выражение $d = $a && $b работает как $d = ($a && $b). А вот выражение $c = $a and $b работает иначе и может быть представлено в виде (($c = $a) and $b).

    Question 7


    What will output code:

    <?php
    $a = 'a';
    for ($i = 0; $i < 40; $i++) {
        echo $a++, PHP_EOL;
    }
    

    Variants of answers:

    1. Figures from 0 to 39 will be displayed, as well as Warning: A non-numeric value encountered in at each iteration
    2. Each iteration will display a '+'
    3. Strange sequence:
      a
      b
      c
      d
      e
      f
      g
      h
      i
      j
      k
      l
      m
      n
      o
      p
      q
      r
      s
      t
      u
      v
      w
      x
      y
      z
      aa
      ab
      ac
      ad
      ae
      af
      ag
      ah
      ai
      aj
      ak
      al
      am
      an

    Correct answer
    3. Странная последовательность:
    a
    b
    c
    d
    e
    f
    g
    h
    i
    j
    k
    l
    m
    n
    o
    p
    q
    r
    s
    t
    u
    v
    w
    x
    y
    z
    aa
    ab
    ac
    ad
    ae
    af
    ag
    ah
    ai
    aj
    ak
    al
    am
    an


    Explanation
    Не все знают, но оператор инкремента можно применять к символам. Из документации:
    PHP следует соглашениям Perl (в отличие от С) касательно выполнения арифметических операций с символьными переменными. Например, в PHP и Perl $a = 'Z'; $a++; присвоит $a значение 'AA', в то время как в C a = 'Z'; a++; присвоит a значение '[' (ASCII-значение 'Z' равно 90, а ASCII-значение '[' равно 91).


    Question 8


    What will output code:

    <?phpclassTestMe{
        publicfunctiontest(){
            if (0) {
                yield32332;
            }
            return [1,2,3];
        }
    }
    $t = new TestMe();
    foreach ($t->test() as $id) {
        echo $id, PHP_EOL;
    }
    echo"The end", PHP_EOL;
    

    Variants of answers:

    1. 12332332
      The end
      

    2. 123
      The end
      

    3. The end
      

    4. 32332
      The end
      


    Correct answer
    3.
    The end
    



    Explanation
    С первого взгляда может показаться, что функция не возвращает генератор, потому что yield выражение недостижимо. Однако, любая функция содержащая yield выражение автоматически становится функцией-генератором. В оригинальном RFC так и написано. В момент первой итерации генератор начинает выполнять код функции с самого начала до первого доступного yield выражения, но поскольку его нет, генератор заканчивает свою работу, так и не передав какие-либо данные в цикл.

    Summarizing


    Answers to questions will post an update to the post on Wednesday, July 4th . If you decide - put the answers under the spoiler, so as not to spoil the other fans. And do not forget to check the personal of Habr after the end of the quiz.

    Enjoy!

    Also popular now: