Перейти к содержимому

Для чего в php

  • автор:

Для чего в php

Приведём пример синтаксиса, используемого для описания функций:

Пример #1 Псевдокод для демонстрации использования функций

function foo ( $arg_1 , $arg_2 , /* . */ $arg_n )
echo «Пример функции.\n» ;
return $retval ;
>
?>

Внутри функции можно использовать любой корректный PHP-код, в том числе другие функции и даже объявления классов.

Имена функций следуют тем же правилам, что и другие метки в PHP. Корректное имя функции начинается с буквы или знака подчёркивания, за которым следует любое количество букв, цифр или знаков подчёркивания. В качестве регулярного выражения оно может быть выражено так: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$ .

Подсказка

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

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

Пример #2 Функции, зависящие от условий

/* Мы не можем вызвать функцию foo() в этом месте,
поскольку она ещё не определена, но мы можем
обратиться к bar() */

if ( $makefoo ) function foo ()
echo «Я не существую до тех пор, пока выполнение программы меня не достигнет.\n» ;
>
>

/* Теперь мы благополучно можем вызывать foo(),
поскольку $makefoo была интерпретирована как true */

if ( $makefoo ) foo ();

function bar ()
echo «Я существую сразу с начала старта программы.\n» ;
>

Пример #3 Вложенные функции

function foo ()
function bar ()
echo «Я не существую пока не будет вызвана foo().\n» ;
>
>

/* Мы пока не можем обратиться к bar(),
поскольку она ещё не определена. */

/* Теперь мы можем вызвать функцию bar(),
обработка foo() сделала её доступной. */

Все функции и классы PHP имеют глобальную область видимости — они могут быть вызваны вне функции, даже если были определены внутри и наоборот.

PHP не поддерживает перегрузку функции, также отсутствует возможность переопределить или удалить объявленную ранее функцию.

Замечание: Имена функций регистронезависимы для символов ASCII от A до Z , тем не менее, предпочтительнее вызывать функции так, как они были объявлены.

Функции PHP поддерживают как списки аргументов переменной длины, так и значения аргументов по умолчанию. Смотрите также описания функций func_num_args() , func_get_arg() и func_get_args() для более детальной информации.

Можно вызывать функции PHP рекурсивно.

Пример #4 Рекурсивные функции

function recursion ( $a )
if ( $a < 20 ) echo " $a \n" ;
recursion ( $a + 1 );
>
>
?>

Замечание: Рекурсивный вызов методов/процедур с глубиной более 100-200 уровней рекурсии может вызвать переполнение стека и привести к аварийному завершению скрипта. В частности, бесконечная рекурсия будет считаться программной ошибкой.

User Contributed Notes

There are no user contributed notes for this page.

  • Функции
    • Функции, определяемые пользователем
    • Аргументы функции
    • Возврат значений
    • Обращение к функциям через переменные
    • Встроенные функции
    • Анонимные функции
    • Стрелочные функции
    • Callback-​функции как объекты первого класса
    • Copyright © 2001-2023 The PHP Group
    • My PHP.net
    • Contact
    • Other PHP.net sites
    • Privacy policy

    Для чего в php

    Unlike in C, PHP references are not treated as pre-dereferenced pointers, but as complete aliases.

    The data that they are aliasing («referencing») will not become available for garbage collection until all references to it have been removed.

    «Regular» variables are themselves considered references, and are not treated differently from variables assigned using =& for the purposes of garbage collection.

    The following examples are provided for clarification.

    1) When treated as a variable containing a value, references behave as expected. However, they are in fact objects that *reference* the original data.

    var = «foo» ;
    $ref1 =& $var ; // new object that references $var
    $ref2 =& $ref1 ; // references $var directly, not $ref1.

    echo $ref1 ; // >Notice: Undefined variable: ref1
    echo $ref2 ; // >foo
    echo $var ; // >foo
    ?>

    2) When accessed via reference, the original data will not be removed until *all* references to it have been removed. This includes both references and «regular» variables assigned without the & operator, and there are no distinctions made between the two for the purpose of garbage collection.

    echo $var ; // >Notice: Undefined variable: var
    echo $ref ; // >foo
    ?>

    3) To remove the original data without removing all references to it, simply set it to null.

    echo $var ; // Value is NULL, so nothing prints
    echo $ref ; // Value is NULL, so nothing prints
    ?>

    4) Placing data in an array also counts as adding one more reference to it, for the purposes of garbage collection.

    Для чего в php

    Переменные в PHP представлены знаком доллара с последующим именем переменной. Имя переменной чувствительно к регистру.

    Имена переменных соответствуют тем же правилам, что и остальные наименования в PHP. Правильное имя переменной должно начинаться с буквы или символа подчёркивания и состоять из букв, цифр и символов подчёркивания в любом количестве. Это можно отобразить регулярным выражением: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

    Замечание: Под буквами здесь подразумеваются символы a-z, A-Z и байты от 128 до 255 ( 0x80-0xff ).

    Замечание: $this — это специальная переменная, которой нельзя ничего присваивать. До PHP 7.1.0 было возможно косвенное присвоение (например, с использованием переменных переменных).

    Подсказка

    Для информации о функциях работы с переменными обращайтесь к разделу функций работы с переменными.

    $var = ‘Боб’ ;
    $Var = ‘Джо’ ;
    echo » $var , $Var » ; // выведет «Боб, Джо»

    $ 4site = ‘ещё нет’ ; // неверно; начинается с цифры
    $_4site = ‘ещё нет’ ; // верно; начинается с символа подчёркивания
    $täyte = ‘mansikka’ ; // верно; ‘ä’ это (Расширенный) ASCII 228.
    ?>

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

    PHP также предлагает иной способ присвоения значений переменным: присвоение по ссылке. Это означает, что новая переменная просто ссылается (иначе говоря, «становится псевдонимом» или «указывает») на оригинальную переменную. Изменения в новой переменной отражаются на оригинале, и наоборот.

    Для присвоения по ссылке, просто добавьте амперсанд (&) к началу имени присваиваемой (исходной) переменной. Например, следующий фрагмент кода дважды выводит ‘ Меня зовут Боб ‘:

    $foo = ‘Боб’ ; // Присваивает $foo значение ‘Боб’
    $bar = & $foo ; // Ссылка на $foo через $bar.
    $bar = «Меня зовут $bar » ; // Изменение $bar.
    echo $bar ;
    echo $foo ; // меняет и $foo.
    ?>

    Важно отметить, что по ссылке могут быть присвоены только именованные переменные.

    $foo = 25 ;
    $bar = & $foo ; // Это верное присвоение.
    $bar = &( 24 * 7 ); // Неверно; ссылка на неименованное выражение.

    function test ()
    return 25 ;
    >

    Хорошей практикой считается инициализировать переменные, хотя в PHP это и не является обязательным требованием. Неинициализированные переменные принимают значение по умолчанию в зависимости от их типа, который определяется из контекста их первого использования: булевы принимают значение false , целые числа и числа с плавающей точкой — ноль, строки (например, при использовании в echo ) — пустую строку, а массивы становятся пустыми массивами.

    Пример #1 Значения по умолчанию в неинициализированных переменных

    // Неустановленная И не имеющая ссылок (то есть без контекста использования) переменная; выведет NULL
    var_dump ( $unset_var );

    // Булевое применение; выведет ‘false’ (Подробнее по этому синтаксису смотрите раздел о тернарном операторе)
    echo $unset_bool ? «true\n» : «false\n» ;

    // Строковое использование; выведет ‘string(3) «abc»‘
    $unset_str .= ‘abc’ ;
    var_dump ( $unset_str );

    // Целочисленное использование; выведет ‘int(25)’
    $unset_int += 25 ; // 0 + 25 => 25
    var_dump ( $unset_int );

    // Использование в качестве числа с плавающей точкой (float); выведет ‘float(1.25)’
    $unset_float += 1.25 ;
    var_dump ( $unset_float );

    // Использование в качестве массива; выведет array(1) < [3]=>string(3) «def» >
    $unset_arr [ 3 ] = «def» ; // array() + array(3 => «def») => array(3 => «def»)
    var_dump ( $unset_arr );

    // Использование в качестве объекта; создаёт новый объект stdClass (смотрите http://www.php.net/manual/ru/reserved.classes.php)
    // Выведет: object(stdClass)#1 (1) < ["foo"]=>string(3) «bar» >
    $unset_obj -> foo = ‘bar’ ;
    var_dump ( $unset_obj );
    ?>

    Полагаться на значения по умолчанию неинициализированных переменных довольно проблематично при включении файла в другой файл, использующий переменную с таким же именем. В случае работы с неинициализированной переменной вызывается ошибка уровня E_WARNING (до PHP 8.0.0 выбрасывалась ошибка уровня E_NOTICE ), за исключением случая добавления элементов в неинициализированный массив. Для обнаружения инициализации переменной может быть использована языковая конструкция isset() .

    User Contributed Notes 5 notes

    13 years ago

    This page should include a note on variable lifecycle:

    Before a variable is used, it has no existence. It is unset. It is possible to check if a variable doesn’t exist by using isset(). This returns true provided the variable exists and isn’t set to null. With the exception of null, the value a variable holds plays no part in determining whether a variable is set.

    Setting an existing variable to null is a way of unsetting a variable. Another way is variables may be destroyed by using the unset() construct.

    print isset( $a ); // $a is not set. Prints false. (Or more accurately prints ».)
    $b = 0 ; // isset($b) returns true (or more accurately ‘1’)
    $c = array(); // isset($c) returns true
    $b = null ; // Now isset($b) returns false;
    unset( $c ); // Now isset($c) returns false;
    ?>

    is_null() is an equivalent test to checking that isset() is false.

    The first time that a variable is used in a scope, it’s automatically created. After this isset is true. At the point at which it is created it also receives a type according to the context.

    $a_bool = true ; // a boolean
    $a_str = ‘foo’ ; // a string
    ?>

    If it is used without having been given a value then it is uninitalized and it receives the default value for the type. The default values are the _empty_ values. E.g Booleans default to FALSE, integers and floats default to zero, strings to the empty string », arrays to the empty array.

    A variable can be tested for emptiness using empty();

    $a = 0 ; //This isset, but is empty
    ?>

    Unset variables are also empty.

    empty( $vessel ); // returns true. Also $vessel is unset.
    ?>

    Everything above applies to array elements too.

    $item = array();
    //Now isset($item) returns true. But isset($item[‘unicorn’]) is false.
    //empty($item) is true, and so is empty($item[‘unicorn’]

    $item [ ‘unicorn’ ] = » ;
    //Now isset($item[‘unicorn’]) is true. And empty($item) is false.
    //But empty($item[‘unicorn’]) is still true;

    $item [ ‘unicorn’ ] = ‘Pink unicorn’ ;
    //isset($item[‘unicorn’]) is still true. And empty($item) is still false.
    //But now empty($item[‘unicorn’]) is false;
    ?>

    For arrays, this is important because accessing a non-existent array item can trigger errors; you may want to test arrays and array items for existence with isset before using them.

    Для чего в php

    For the ‘late static binding’ topic I published a code below, that demonstrates a trick for how to setting variable value in the late class, and print that in the parent (or the parent’s parent, etc.) class.

    class cA
    /**
    * Test property for using direct default value
    */
    protected static $item = ‘Foo’ ;

    /**
    * Test property for using indirect default value
    */
    protected static $other = ‘cA’ ;

    public static function method ()
    print self :: $item . «\r\n» ; // It prints ‘Foo’ on everyway. 🙁
    print self :: $other . «\r\n» ; // We just think that, this one prints ‘cA’ only, but. 🙂
    >

    public static function setOther ( $val )
    self :: $other = $val ; // Set a value in this scope.
    >
    >

    class cB extends cA
    /**
    * Test property with redefined default value
    */
    protected static $item = ‘Bar’ ;

    public static function setOther ( $val )
    self :: $other = $val ;
    >
    >

    class cC extends cA
    /**
    * Test property with redefined default value
    */
    protected static $item = ‘Tango’ ;

    public static function method ()
    print self :: $item . «\r\n» ; // It prints ‘Foo’ on everyway. 🙁
    print self :: $other . «\r\n» ; // We just think that, this one prints ‘cA’ only, but. 🙂
    >

    /**
    * Now we drop redeclaring the setOther() method, use cA with ‘self::’ just for fun.
    */
    >

    class cD extends cA
    /**
    * Test property with redefined default value
    */
    protected static $item = ‘Foxtrot’ ;

    /**
    * Now we drop redeclaring all methods to complete this issue.
    */
    >

    cB :: setOther ( ‘cB’ ); // It’s cB::method()!
    cB :: method (); // It’s cA::method()!
    cC :: setOther ( ‘cC’ ); // It’s cA::method()!
    cC :: method (); // It’s cC::method()!
    cD :: setOther ( ‘cD’ ); // It’s cA::method()!
    cD :: method (); // It’s cA::method()!

    14 years ago

    Little static trick to go around php strict standards .
    Function caller founds an object from which it was called, so that static method can alter it, replacement for $this in static function but without strict warnings 🙂

    error_reporting ( E_ALL + E_STRICT );

    function caller () $backtrace = debug_backtrace ();
    $object = isset( $backtrace [ 0 ][ ‘object’ ]) ? $backtrace [ 0 ][ ‘object’ ] : null ;
    $k = 1 ;

    return isset( $backtrace [ $k ][ ‘object’ ]) ? $backtrace [ $k ][ ‘object’ ] : null ;
    >

    public $data = ‘Empty’ ;

    function set_data () b :: set ();
    >

    static function set () // $this->data = ‘Data from B !’;
    // using this in static function throws a warning .
    caller ()-> data = ‘Data from B !’ ;
    >

    $a = new a ();
    $a -> set_data ();
    echo $a -> data ;

    ?>

    Outputs: Data from B !

    No warnings or errors !

    17 years ago

    You use ‘self’ to access this class, ‘parent’ — to access parent class, and what will you do to access a parent of the parent? Or to access the very root class of deep class hierarchy? The answer is to use classnames. That’ll work just like ‘parent’. Here’s an example to explain what I mean. Following code

    class A
    protected $x = ‘A’ ;
    public function f ()
    return ‘[‘ . $this -> x . ‘]’ ;
    >
    >

    class B extends A
    protected $x = ‘B’ ;
    public function f ()
    return ‘ x . ‘>’ ;
    >
    >

    class C extends B
    protected $x = ‘C’ ;
    public function f ()
    return ‘(‘ . $this -> x . ‘)’ . parent :: f (). B :: f (). A :: f ();
    >
    >

    $a = new A ();
    $b = new B ();
    $c = new C ();

    15 years ago

    Nice trick with scope resolution
    class A
    public function TestFunc ()
    return $this -> test ;
    >
    >

    class B
    public $test ;

    public function __construct ()
    $this -> test = «Nice trick» ;
    >

    public function GetTest ()
    return A :: TestFunc ();
    >
    >

    $b = new B ;
    echo $b -> GetTest ();
    ?>

    will output

    16 years ago

    This is a solution for those that still need to write code compatible with php 4 but would like to use the flexibility of static variables. PHP 4 does not support static variables within the class scope but it does support them within the scope of class methods. The following is a bit of a workaround to store data in static mode in php 4.

    Note: This code also works in PHP 5.

    (Tested on version 4.3.1+)

    The tricky part is when using when arrays you have to do a bit of fancy coding to get or set individual elements in the array. The example code below should show you the basics of it though.

    class StaticSample
    //Copyright Michael White (www.crestidg.com) 2007
    //You may use and modify this code but please keep this short copyright notice in tact.
    //If you modify the code you may comment the changes you make and append your own copyright
    //notice to mine. This code is not to be redistributed individually for sale but please use it as part
    //of your projects and applications — free or non-free.

    //Static workaround for php4 — even works with arrays — the trick is accessing the arrays.
    //I used the format s_varname for my methods that employ this workaround. That keeps it
    //similar to working with actual variables as much as possible.
    //The s_ prefix immediately identifies it as a static variable workaround method while
    //I’m looking thorugh my code.
    function & s_foo ( $value = null , $remove = null )
    static $s_var ; //Declare the static variable. The name here doesn’t matter — only the name of the method matters.

    if( $remove )
    if( is_array ( $value ))
    if( is_array ( $s_var ))
    foreach( $value as $key => $data )
    unset( $s_var [ $key ]);
    >
    >
    >
    else
    //You can’t just use unset() here because the static state of the variable will bring back the value next time you call the method.
    $s_var = null ;
    unset( $s_var );
    >
    //Make sure that you don’t set the value over again.
    $value = null ;
    >
    if( $value )
    if( is_array ( $value ))
    if( is_array ( $s_var ))
    //$s_var = array_merge($s_var, $value); //Doesn’t overwrite values. This adds them — a property of the array_merge() function.
    foreach( $value as $key => $data )
    $s_var [ $key ] = $data ; //Overwrites values.
    >
    >
    else
    $s_var = $value ;
    >
    >
    else
    $s_var = $value ;
    >
    >

    echo «Working with non-array values.
    » ;
    echo «Before Setting: » . StaticSample :: s_foo ();
    echo «
    » ;
    echo «While Setting: » . StaticSample :: s_foo ( «VALUE HERE» );
    echo «
    » ;
    echo «After Setting: » . StaticSample :: s_foo ();
    echo «
    » ;
    echo «While Removing: » . StaticSample :: s_foo ( null , 1 );
    echo «
    » ;
    echo «After Removing: » . StaticSample :: s_foo ();
    echo «


    » ;
    echo «Working with array values
    » ;
    $array = array( 0 => «cat» , 1 => «dog» , 2 => «monkey» );
    echo «Set an array value: » ;
    print_r ( StaticSample :: s_foo ( $array ));
    echo «
    » ;

    //Here you need to get all the values in the array then sort through or choose the one(s) you want.
    $all_elements = StaticSample :: s_foo ();
    $middle_element = $all_elements [ 1 ];
    echo «The middle element: » . $middle_element ;
    echo «
    » ;

    $changed_array = array( 1 => «big dog» , 3 => «bat» , «bird» => «flamingo» );
    echo «Changing the value: » ;
    print_r ( StaticSample :: s_foo ( $changed_array ));
    echo «
    » ;

    //All you have to do here is create an array with the keys you want to erase in it.
    //If you want to erase all keys then don’t pass any array to the method.
    $element_to_erase = array( 3 => null );
    echo «Erasing the fourth element: » ;
    $elements_left = StaticSample :: s_foo ( $element_to_erase , 1 );
    print_r ( $elements_left );
    echo «
    » ;
    echo «Enjoy!» ;

    • Классы и объекты
      • Введение
      • Основы
      • Свойства
      • Константы классов
      • Автоматическая загрузка классов
      • Конструкторы и деструкторы
      • Область видимости
      • Наследование
      • Оператор разрешения области видимости (::)
      • Ключевое слово static
      • Абстрактные классы
      • Интерфейсы объектов
      • Трейты
      • Анонимные классы
      • Перегрузка
      • Итераторы объектов
      • Магические методы
      • Ключевое слово final
      • Клонирование объектов
      • Сравнение объектов
      • Позднее статическое связывание
      • Объекты и ссылки
      • Сериализация объектов
      • Ковариантность и контравариантность
      • Журнал изменений ООП
      • Copyright © 2001-2023 The PHP Group
      • My PHP.net
      • Contact
      • Other PHP.net sites
      • Privacy policy

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *