Тестирование — oDesk PHP5 Test

Пару дней назад было немного свободного времени, решил проверить — «какой с меня программист». На сайте oDesk.com, на котором я зарегистрирован, есть возможность пройти квалификационное тестирование по большому количеству языков программирования и технологий, проверить свои знания и получить оценку. Я выбрал PHP5 Test. Спустя полчаса умственной работы я был удовлетворен — получил 4.20 из 5.00 возможных, и попал в Top 20%. Мелочь, а приятно 🙂

В процессе тестирования я сохранил вопросы и варианты ответов, с тем, чтобы написать маленькое пособие по подготовке к тесту. Ниже Вы можете найти вопросы, варианты ответов, и мой ответ на этот вопрос. Возможно, на некоторые вопросы я ответил неправильно, и мы можем вместе внести исправления. Надеюсь на вашу подсказку.

И еще: если мой пост оказался полезен для Вас — нажмите на рекламный баннер, расположенный под этим текстом. Вам это ничего не стоит, а мне — пригодится. Спасибо заранее! 🙂

Собственно, вот вопросы. Правильные, на мой взгляд, ответы, я выделил цветом:

Question (many answers): What is true regarding $a + $b where both of them are arrays?

a. Duplicated keys are NOT overwritten
b. $b is appended to $a
c. The + operator is overloaded
d. This produces a syntax error

Question: You have two strings, which you want to concatenate.

$str1 = ‘Have a ‘;
$str2 = ‘Nice Day’;
The fastest way would be:
a. $str1.Concat($str2);
b. $str1.$str2;
c. “$str1$str2”;
d. None of the above

Question: Which of the following pair have non-associative equal precedence?

a. +,-
b. ==,!=
C. «,»
d. &=,|=

Question:Which of the following variables is not related to file uploads?

a. max_file_size
b. max_execution_time
c. post_max_size
d. max_input_time

Question: You have a 2D array in PHP:

$array = array(array(141,151,161), 2,3, array(101, 202, 303));
You want to display all the values in the array The correct way is:

a.

function DisplayArray($array) {
   foreach ($array as $value) {
      if (array_valid($value)) {
         DisplayArray($value);
      } else {
         echo $value. “<br>”;
      }
   }
}

DisplayArray($array);

b.

function DisplayArray($array) {
   for ($array as $value) {
      if (valid_array($value)) {
         DisplayArray($value);
      } else {
         echo $value. “<br>”;
      }
   }
}

DisplayArray($array);

c.

function DisplayArray($array) {
   for ($array as $value) {
      if (is_array($value)) {
         DisplayArray($value);
      } else {
         echo $value. “&ltbr>”;
      }
   }
} 

DisplayArray($array);

d.

function DisplayArray($array) {
   foreach ($array as $value) {
      if (is_array($value)) {
         DisplayArray($value);
      } else {
         echo $value “&ltbr>”;
      }
   }
}

DisplayArray($array);

Right answer: d.

Question: Multiple select/load is possible with:

a. Checkbox
b. Select
c. File
d. All of the above

Question: The following php variables are declared:

$company = ‘ABS Ltd’;
$$company =‘, Sydney’;
Which of the following is not a correct way of printing ‘ABS Ltd. Sydney’?

a. echo “$company $$company”;
b. echo “$company ${$company}”;
c. echo “$company ${‘ABS Ltd‘}“;
d. echo “$company {$$company}”;

Question (many answers)

We have two variable definitions:
1. 023
2. x23

Choose the correct options:
a. 1 is octal
b. 2 is hexadecimal
c. 2 is octal
d. 1 is hexadecimal

Question: Which of the following is a predefined constant?

a. TRUE
b. FALSE
c. NULL
d. _FILE_
e. CONSTANT

Question (many answers): Which of the following variable names are invalid?

a. $var_1
b. $var1
c. $var-1
d. $var/1
e. $vl

Question (many answers): Which of the following are not considered as boolean False?

a. FALSE
b. 0
c. “0”
d. “FALSE”
e. 1
f. NULL

Question: Which of the following regular expressions can be used to check the validity of an e-mail addresss?

a. ^[^@ ]+@[^@ ]+\.[“@ ]+$
b. ^[^@ ]+@[^@ ]+[^@ ]+$
c. $[^@ ]+@[^@ ]+\[^@ ]+^
d. $[^@ ]+@[^@ ]+[^@ ]+^

Question: Which of the following type cast is not correct?

$fig=23;
$varbl= (real) $fig;
$varb2 = (double) $flg;
$varb3 = (decimal) $flg;
$varb4 = (bool) $fig;

a. real
b. double
c. decimal
d. boolean

Question: Which of the following statements is not true with regard to abstract classes in php5?

a. Abstract classes are introduced in PHP5
b. A class with a single abstract method must be declared abstract
c. Abstract class can contain non abstract methods
d. Abstract method must have method definition and can have optional empty braces following it

Question: What do you infer from the following code?

$str = ‘Dear Customer,\nThanks for your query. We will reply very soon\n Regards,\n Customer Service Agent’;
print $str;

a. Only first \n character will be recognised and new line will be inserted
b. Last \n will not be recognised and only first two parts will come in new lines
c. All the \n will work and text will be printed on respective new lines.
d. All will be printed on one line irrespective of the \n.

Question: Which of the following characters are taken care of by htmlspecialchars?

a. <
b. >
c. single quote
d. double quote
e. &
f. All of the above

Question: What will be the output of the following code?

$a = 10;
if($a > 5 OR < 15)
echo “true”;
else
echo “false”

a. true
b. false
c. No output
d. Parse Error

Question: If expire parameter of setCookie function is not specified then:

a. Cookie will never expire
b. Cookie will expire with closure of the browser
c. Cookie will expire with within 30 minutes
d. Cookie will expire in 24 hours

Question: You need to check the size of a file in PHP function.

$size=X(filename);

Which function will suitably replace ‘X’ ?
a. filesize
b. size
c. sizeofFile
d. getSize

Question: Which of the following text manipulation functions is supported by PHP?

a. strtoupper()
b. ucfirst()
c. strtolower()
d. str_split()
e. All of the above

Question: Which of the following is a correct declaration?

a. static $varb = array(1 ,‘var, 3);
b. static $varb = 1+(2*9O);
c. static $varb = sqrt(81);
d. static $varb = new Object;

Question: You wrote following script to check for the right category:

1<?php
2 $cate=5
3 …
4 …
5
6 if ($cate==5)
7 {
8 ?>
9 Correct category!
10 <?php
11 } else {
12 ?>
13 Incorrect category!
14 <?php
15 }
16 ?>

What will be the output of the program if value of’cate’ remains 5?
a. Correct category!
b. Incorrect category!
c. Error due to use of invalid operator in line 6:”if ($cate=5)»
d. Error due to incorrect syntax at line 8, 10, 12 and 14

Question: If visibility is not defined for a method/member then it is treated as public static.

a. True
b. False

Question (many answers): Which of the following statements is incorrect with regard to interfaces?

a. A class can implement multiple interfaces
b. An abstract class cannot implement multiple interlaces
c. An interlace can extend multiple interfaces
d. Methods with same name, arguments, and sequence can exist in the different interlaces implemented by a class

Question: Which of the following is a Ternary Operator?

a. &
b. =
c. : ?
d. ? :
e. +=
f. &&

Question: Which of the following are the valid PHP data types?

a. resource
b. null
c. boolean
d. string
e. Both a and c
f. Both c and d
g. All of the above (Обоснование)

Question: You are using sessions and session_register() to register objects. These objects are serialized automatically at the end of each PHP page and are de-serialized automatically on each of the following pages Is this true or false?

a. True
b. False

Question: What will be the output of the following code?

$Rent = 250;
function Expenses($Other) {
   $Rent = 250 + $Other;
   return $Rent;
}

Expenses(50),
echo $Rent;

a. 300
b. 250
c. 200
d. Program will not compile

Question: What will be the result of the following expression:

6+4 * 9-3

a. 60
b. 87
c. 39
d. 30

Question: Does php 5 support exceptions?

a. Yes
b. No

Question (many answers): Which of the following printing construct/function accepts multiple parameters?

a. echo
b. print
c. printf
d. Allof the above

Question: What will be the output of the following code?

$var = 10;
function fn() {
   $var=20;
   return $var;
}

Fn();
echo $var;

a. 10
b. 20
c. Undefined Variable
d. Syntax Error

Question: Which of the following is not true regarding XForms?

a. PHP provides support for XForm
b. It can be used on PDF documents
c. The data is sent in XML format
d. The action and method parameters are defined in the body

Question: How would you start a session?

a. session(start);
b. session();
c. session_start();
d. begin_sesion();

Question: How would you store order number (34) in an OrderCookie’?

a. setcookie(«OrderCookie”, 34);
b. makeCookie(”OrderCookie”, 34);
c. Cookie(«OrderCookie”, 34);
d. OrderCookie(34);

Question: What will be the output of the following code?

function fn(&$var) {
   $var = $var - ($var/l0*5);
   return $var;
)
echo fn(100);

a.100
b. 50
c. 98
d. Error message
e. None of the above

Question: What will be the result of following operation?

print 4 << 5;
a. 3
b. 128
c. 120
d. 6

Question: Which of the following is not supported in PHP5?

a. Type Hinting
b. Reflection
c. Magic Methods
d. Muftiple Inheritance
e. Object Cloning

Question: Which of the following is not a valid PHP parser tag?

a. script
b. ?p
c. %
d. ?php

Question: What will be the output of following code?

$a=10;
echo “Value of a =$a”;

a. Value of a=10
b. Value of a=$a
c. Undefined
d. Syntax Error

Question: You need to keep an eye on the existing number of objects of a given class without introducing a non-class member variable.Which of the following makes this happen?

a. Add a member variable that gets incremented in the default constructor and decremented in the destructor
b. Add a local variable that gets incremented in each constructor and decremented in the destructor
c. Add a static member variable that gets incremented in each constructor and decremented in the destructor
d. This cannot be accomplished since the creation of objects is being done dynamically via “new”

Question: Which of the following multithreaded servers allow PHP as a plug-in?

a. Netscape FastTrack
b. Microsoft’s Internet Information Server
c. O’Reilly’s WebSite Pro
d. Allof the above

Question: Which of the following is used to maintain the value of a variable over different pages?

a. static
b. global
c. session_register()
d. Noneoftheabove

Question: Which of the following variable declarations within a class is invalid in PHP5?

a. private $type = ‘moderate’;
b. internal $term = 3;
c. public $amnt = ‘500’;
d. protected $name = ‘Quantas Private Limited’;

Question: Consider the following two statements:

1 while (expr) statement
2 while (expr): statement endwhile;

Which of the following are true in context of the given statements?
a. 1 is correct and 2 is wrong
b. 1 is wrong and 2 is correct
c. Both 1 & 2 are wrong
d. Both 1 & 2 are correct

Question: You have defined three variables $to, $subject, and $body to send an email. Which of the following methods would you use for sending an email?

a. mail($to,$subject,$body)
b. sendmail($to,$subject,$body)
c. mail(to,subject,body)
d. sendmail(to,subject,body)

Question: What is the output of the following code?

function vec_add (&Sa, Sb) {
   $a[X] += $b[’x’];
   $a[y] += $b[’y’];
   $a[Z] += $b['Z'];
}
$a = array (x => 3, y => 2, z => 5);
$b = array (x => 9, y => 3, z => -7);

vec_add (&$a, $b);
print_r ($a);

a. Array
(
[X] => 9
[y] => 3
[Z] => -7

b. Array
[x] => 3
[y] => 2
[z] => 5

c. Array
[xJ =>12
[yJ => 5
[z] => -2

d. Error
e. None of the above

Question: In your PHP application you need to open a file. You want the application to issue a warning and continue execution, in case the file is not found The ideal function to be used is:

a. include()
b. require()
c. nowarn()
d. getFile(false)

Question (many answers); Which of the the following are PHP file upload related functions?

a. upload_file()
b. is_uploaded_file()
c. move_uploaded_file()
d. Noneoftheabove

Question: Which of the following attribute is needed for file upload via form?

a. enctype=”multipart/formdata”
b. enctype=”singlepart/data’
c. enctype=»file”
d. enctype=»form-data/file”

Question: Variable/functions in PHP don’t work directly with:

a. echo()
b. isset()
c. print()
d. All of the above

Question: Which of the following is a PHP resource?

a. Domxml document
b. Odbc link
c. File
d. All of the above (Объяснение)

Question: The inbuilt function to get the number of parameters passed is:

a. arg_num()
b. func_args_count()
c. func_num_args()
d. None of the above

Question: For the following code:

function Expenses() {
   function Salary() {
      function Loan() {
         function Balance() {
         }
      }
   }
}

Which of the following sequence will run successfully?
a. Expenses();Salary();Loan; Balance();
b. Salary();Expenses();Loan(); Balance();
c. Expenses();Salary();Balance();Loan();
d. Balance();Loan();Salary(); Expenses();

Question: What will be the output of the following code?

echo 30 * 5.7

a. 150.7
b. 1507
c. 171
d. you can’t concatenate integers
e. error will occur

Question: Which of the following is correct with regard to echo and print?

a. echo is a construct and print is a function
b. echo is a function and print is a construct
c. Both are functions
d. Both are constructs

Question: Which of the following is not a file related function in PHP?

a. fclose
b. fopen
c. fwrite
d. fgets
e. fappend

Question: Which of the following variables are supported by ‘str_replace’ function?

a. Integer
b. String
c. Boolean
d. Array

Question: Which of the following are useful for method overloading?

a. _call,_get,_set
b. _get,_set,_load
c. _get,_set,_isset
d. _overload

Question: What will be the output of the following code?

var_dump (3*4);

a. int(3*4)
b. int(12)
c. 3*4
d. 12
e. None of the above

Question: You need to count the number of parameters given in the URL by a POST operation. The correct way is:

a. count($POST_VARS);
b. count($POST_VARS_PARAM);
c. count($_POST);
d. count($HTTP_POST_PARAM);

Question: Consider the following class:

1 class Insurance
2 {
3 function clsName()
4 {
5 echo get_class($this);
6 }
7 }
8 $cl = new Insurance();
9 Scl->clsName();
10 lnsurance::clsName();

Which of the following Lines should be commented to print the class name without errors?
a. Line 8 and 9
b. Line 10
c. Line 9 and 10
d. All the three lines 8,9, and 10 should be left as it is.

Question: Which of the following statement is not correct for PHP?

a. it is a server side scripting language
b. A php file may contain text, html tags or scripts
c. it can run on windows and Linux systems only
d. it is compatible with most of the common servers used today

Question: Which of the following functions output text?

a. echo()
b. print()
c. println()
d. display()

Question: Which of the following crypto ¡n PHP returns longest hash value?

a. md5()
b. sha1()
c. crc32()
d. All return same length hash

Question: The value of a local variable of a function has to be retained over multiple calls to that function. How should that variable be declared?

a. local
b. global
c. static
d. None of the above

Question: Does PHP provide the goto keyword in latest version?

a. Yes
b. No

P.S. Пока писал заметку на сайт, нашел у себя пару ошибок. Нужно будет попробовать пересдать этот тест, улучшить показатель 😉

The On Demand Global Workforce - oDesk

Тестирование — oDesk PHP5 Test: 42 комментария

  1. Hi!

    Спасибо за ответы! С несколькими я не согласна.
    Вот здесь мои ответы

    Question: Which of the following is a correct declaration?

    a. static $varb = array(1 ,‘var’, 3); — correct
    b. static $varb = 1+(2*9O);
    c. static $varb = sqrt(81);
    d. static $varb = new Object;

    Question: What will be the output of the following code?

    echo 30 * 5.7

    a. 150.7
    b. 1507
    c. 171 — correct (можно 3 * 57)
    d. you can’t concatenate integers
    e. error will occur

    Question: Which of the following is correct with regard to echo and print?

    a. echo is a construct and print is a function
    b. echo is a function and print is a construct
    c. Both are functions
    d. Both are constructs — correct

    Question: What is the output of the following code?

    function vec_add (&Sa, Sb) {
    $a[X] += $b[’x’];
    $a[y] += $b[’y’];
    $a[Z] += $b[‘Z’];
    }
    $a = array (x => 3, y => 2, z => 5);
    $b = array (x => 9, y => 3, z => -7);

    vec_add (&$a, $b);
    print_r ($a);

    a. Array
    (
    [X] => 9
    [y] => 3
    [Z] => -7

    b. Array
    [x] => 3
    [y] => 2
    [z] => 5

    c. Array — correct
    [xJ =>12
    [yJ => 5
    [z] => -2

    d. Error
    e. None of the above

    Question: What will be the output of the following code?

    function fn(&$var) {
    $var = $var — ($var/l0*5);
    return $var;
    )
    echo fn(100);

    a.100
    b. 50
    c. 98
    d. Error message — correct
    e. None of the above

    Question: What will be the output of the following code?

    $Rent = 250;
    function Expenses($Other) {
    $Rent = 250 + $Other;
    return $Rent;
    }

    Expenses(50),
    echo $Rent;

    a. 300
    b. 250 correct
    c. 200
    d. Program will not compile

    Question: You have a 2D array in PHP:

    $array = array(array(141,151,161), 2,3, array(101, 202, 303));
    You want to display all the values in the array The correct way is:

    a.

    function DisplayArray($array) {
    foreach ($array as $value) {
    if (array_valid($value)) {
    DisplayArray($value);
    } else {
    echo $value. “”;
    }
    }
    }

    DisplayArray($array);

    b.

    function DisplayArray($array) {
    for ($array as $value) {
    if (valid_array($value)) {
    DisplayArray($value);
    } else {
    echo $value. “”;
    }
    }
    }

    DisplayArray($array);

    c.

    function DisplayArray($array) {
    for ($array as $value) {
    if (is_array($value)) {
    DisplayArray($value);
    } else {
    echo $value. “&ltbr>”;
    }
    }
    }

    DisplayArray($array);

    d.

    function DisplayArray($array) {
    foreach ($array as $value) {
    if (is_array($value)) {
    DisplayArray($value);
    } else {
    echo $value “&ltbr>”;
    }
    }
    }

    DisplayArray($array);

    Right answer: d.

        1. как минимум в 2 ответах заметил ошибки в самом переводе, автор при ответе на вопросы не замечает «отрицание»
          ну и в других ответах есть ошибки
          в частности goto есть как минимум в 5.3

          1. Давайте конкретнее, совместными усилиями исправим.

  2. А разве в оригинале на сайте oDesk в скобках ($var/l0*5) именно такой текст? Если да — тогда естественно будет ошибка. Иначе мой вариант правильный.

    function fn(&$var) {
    $var = $var – ($var/l0*5);
    return $var;
    )
    echo fn(100);

  3. Какая разница что в скобках? Разве так сложно было проверить, набрав код в PHP?
    Получается ошибка «Only variables can be passed by reference».
    Ну нельзя передавать число и принимать его по ссылке.

    1. Согласен, «слона» я не заметил. Передавать значение (например, «echo fn(100);») , а не переменную — нельзя. А я зациклился на этом — ($var/l0*5), что «l0» — это не 10.
      Нереально во время ответов на вопросы проверить правильность в PHP. Спасибо за подсказку, исправил.

  4. Не знаю насколько это актуально, но выскажу свои соображения.

    Question: We have two variable definitions:
    1. 023
    2. x23

    Choose the correct options:
    a. 1 is octal
    b. 2 is hexadecimal
    c. 2 is octal
    d. 1 is hexadecimal

    По-моему, правильный вариант один: «a. 1 is octal».
    Потому что hexademical задаётся 0x23.
    А значит во 2-м мы имеем строку.
    Вариант d. не может быть правильным, потому что это octal, а число не может быть одновременно и hexademical и octal (а 0XXX — это именно octal формат).

    Question: Which of the following is a predefined constant?

    a. TRUE
    b. FALSE
    c. NULL
    d. _FILE_
    e. CONSTANT

    _FILE_ — это predefined constant, достаточно написать скрипт в одну строку: echo _FILE_
    А вот вариант «e» не задан.

    Question: Which of the following type cast is not correct?

    $fig=23;
    $varbl= (real) $fig;
    $varb2 = (double) $flg;
    $varb3 = (decimal) $flg;
    $varb4 = (bool) $fig;

    a. real
    b. double
    c. decimal
    d. boolean

    Здесь с вариантов «a» всё нормально, правильный ответ вариант «c» (достаточно ввести предлагаемый код в пхп файл и посмотреть).

    Question: Which of the following statements is not true with regard to abstract classes in php5?

    a. Abstract classes are introduced in PHP5
    b. A class with a single abstract method must be declared abstract
    c. Abstract class can contain non abstract methods
    d. Abstract method must have method definition and can have optional empty braces following it

    Здесь правильный ответ «c» (http://php.su/learnphp/phpoo/?php5_2 8 абзац)

    Question: Which of the following is a correct declaration?

    a. static $varb = array(1 ,‘var, 3);
    b. static $varb = 1+(2*9O);
    c. static $varb = sqrt(81);
    d. static $varb = new Object;

    Ответ «c» неправильный, потому что в объявлении переменных в классе не может использоваться выражение в качестве начального значения переменной.
    Правильный ответ «a».

    Question: Which of the following are the valid PHP data types?

    a. resource
    b. null
    c. boolean
    d. string
    e. Both a and c
    f. Both c and d
    g. All of the above

    Здесь правильный ответ «g» (http://php.su/learnphp/datatypes/).

    Question: You are using sessions and session_register() to register objects. These objects are serialized automatically at the end of each PHP page and are de-serialized automatically on each of the following pages Is this true or false?

    a. True
    b. False

    Здесь правильный ответ «a» (http://php.net/manual/ru/function.session-register.php читайте в самом конце страницы).

    Question: Which of the following is not a valid PHP parser tag?

    a. script
    b. ?p
    c. %
    d. ?php

    Здесь правильный ответ «b» (http://www.php.net/manual/en/language.basic-syntax.phptags.php).

    Question: Consider the following two statements:

    1 while (expr) statement
    2 while (expr): statement endwhile;

    Which of the following are true in context of the given statements?
    a. 1 is correct and 2 is wrong
    b. 1 is wrong and 2 is correct
    c. Both 1 & 2 are wrong
    d. Both 1 & 2 are correct

    Тут правильный «d» (http://php.net/manual/en/control-structures.while.php).

  5. ya bi poprosil tex kto otvechaet na voprosi nespesha otvechat,oto vashi otveti vvodyat lyudey v zablujdenie.Vot naprimer na vopros «Which of the following statements is not true with regard to abstract classes in php5?» otvet d na moy vsglyad potomuchto abstractniy class mojet imet ne obstracniy method.primer abstract class A{
    function goo(){}
    }

    1. В моем начальном посте ответ правильный, d).
      Вот ссылка из документации «PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature — they cannot define the implementation.»

      А товарищ выше, который утверждает, что правильный ответ c) приводит правильную ссылку, а вот правильный ответ выбрать не может — абстрактный класс может! содержать обычные, не абстрактные методы.

  6. Menya bolshe vsego volnuet otvet na vopros Which of the following statements regarding PHP forms, are correct?

    a. In PHP, the predefined $_POST variable is used to collect values in a form with method=»post»
    b. In PHP, the predefined $_GET variable is used to collect values in a form with method=»get»
    c. In PHP, the predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE
    d. Information sent from a form with the POST method is invisible to others and has an 8MB limit on the amount of information to send, which cannot be changed. Tut ya somnivayus v variante d. potomuchto napisano method post nevidim dlya drugix.Kto eti drugie?dlya lyudey -da,a dlya skripta net

    1. Все пункты для данного вопроса верны. Если с первыми тремя (a..c) и так понятно, то по последнему d) тоже все верно, и вот почему:
      That depends on the value of the PHP configuration directive POST_MAX_SIZE which is usually set to 8 MB (~8 million characters).

      Также, невидимость параметров здесь в сравнении с GET-методом.

      1. izveni no na schot a i b otvetov ya nesoglasen,potomuchto $_POST i $_GET eto massivi v kotorix xranyatsya dannie ot sootvetstvuyushix methodov,oni nesobirayut dannie,a methodi sobirayut dannie i zapisivayut vnix.Tut otvet ili c ili c,d.Voobshe mutno s otvetom d

  7. Which of the following printing construct/function accepts multiple parameters?

    a. echo
    b. print
    c. printf
    d. All of the above
    Tut vo pervix nado razobratsya kak stavitsya vopros,ya tak i ne ponyal esli sprashivaetsya kakaya function prinemaet mnogo param,to otvet c.printf,a esli i construkciy to i echo toje,voobshe neponyatno

      1. Не верно. Mixed это «любой тип данных», а не неизвестное количество параметров.
        Правильный ответ — a и c
        void echo ( string $arg1 [, string $… ] )
        int printf ( string $format [, mixed $args [, mixed $… ]] )
        int print ( string $arg )

        Выражение
        print $a, $b;
        Вызовет ошибку: PHP Parse error: syntax error, unexpected ‘,’ in php shell code on line 1

  8. Na vopros «The value of a local variable of a function has to be retained over multiple calls to that function. How should that variable be declared?»
    Ya bi otvetil static,
    function foo(){
    static $a=0;
    echo $a++;
    }
    foo();
    foo();
    foo();
    Ya ponyal tak,xotyat soxranit localnuyu peremennuyu,pomoemu on nedoljna bit svyazanna s globalnoy ,ili vopros netak ponyal?

    1. В оригинальном посте ответ правильный, вариант b) global.
      Если объявить переменную, как глобальную, внутри функции, значение этой переменной будет доступно в глобальном скопе, т.е. будет передаваться между вызовами процедур.

    1. В моем списке такого вопроса нет, но правильный ответ c) $REMOTE_ADDR.
      Переменная будет существовать при условии, что включена переменная в php.ini — register_globals=On,
      т.к. c. $REMOTE_ADDR, это переменная из массива $_SERVER ($_SERVER[‘REMOTE_ADDR’]).

    1. Правильный ответ — a. b. c. d, т.е. все перечисленные варианты поддерживаются.
      Исправил в основном списке.

      Небольшой пример:
      $search = true;
      $replace = ‘True’;
      $subject = ‘What is the right answer for bool variable? Answer: 1’;
      echo str_replace($search, $replace, $subject);

      На экране будет:
      What is the right answer for bool variable? Answer: True

Добавить комментарий