Удаление всех переменных php

Удаление всех переменных не завершая самого скрипта!

Как можно в ходе выполнения скрипта удалить все переменные, которые были ранее объявлены?

Просто мне нужно пустить скрипт по кругу, обычным циклом, а множество переменных могут иметь остатки данных после предыдущего шага цикла.

PS: За ‘script.php’ скрывается множество других скриптов, которые вызывают друг-друга, он просто главный, скажем так, не считая ‘index.php’, в котором этот цикл собственно и запускается

tostrss

Мой дом здесь!

В пхп нельзя просто взять массово убить все переменные кроме каких-то. Ведь тогда могу убится нужные, поэтому надо убивать точечно через unset();

_AlexSK_

Постоялец

bugargen

Местный житель

В пхп нельзя просто взять массово убить все переменные кроме каких-то. Ведь тогда могу убится нужные, поэтому надо убивать точечно через unset();

Жаль, очень жаль
Хотя, по идеи, могли бы придумать такую ф-цию. Ведь это очевидно — есть переменные, которые PHP создаёт-мусолит, а есть, которые явно прописаны в скрипте — вот их и нужно удалять. В общем — х.з.
Я ещё когда начинал писать этот скрипт — думал, что может лучше подчищать за собой переменные, но смысла в этом небыло никакого, только с точки зрения грамотности кода. А теперь — понадобилось, но все их перебирать сложно. О причине такой необходимости ниже.

Можно и Крон заюзать. Но это всё мне не подходит совершенно!
Мне нужен не просто запуск скрипта несколько раз, а запуск скрипта столько раз, сколько встретится каталогов в указанной директории + к этому наименования этих каталогов идут в качестве передаваемого значения + счётчик.

В общем, придётся идти длинным путём.

tostrss

Мой дом здесь!

В чем проблема вручную удалять крупные переменные? В конце концов, можете сами написать свой сборщик мусора, в чем проблема то?

_AlexSK_

Постоялец

Да, в таком случае, лучше пройтись по файлам-скриптам и подчистить за собой переменные. По-идее, это не займет много времени.

potuga

Гуру форума

А лучше всего взять за правило перед использованием той переменной, где потенциально могут содержаться ненужные данные, всегда юзать unset() и проблем потом не будет

ZCFD

Мой дом здесь!

1)require_once ? так он пордключится всего один раз. По определению
так что там должно быть require. ну или я не понял идею и прошу мне объяснить. Т.к. интересно )))
2) я хз конечно. просто пердположение — вынеси require(‘script.php’); в отдельную функцию и в цикле вызывай уже эту функцию. Т.е. итерация заканчивается после выполнения scripts.php. При вызове функции все созданные в ней переменные являются локальными по умочанию. И при выходе из функции должны удаляться. — В теории.

Читайте также:  Styles

RolCom

Постоялец

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

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

bugargen

Местный житель

я хз конечно. просто пердположение — вынеси require(‘script.php’); в отдельную функцию и в цикле вызывай уже эту функцию. Т.е. итерация заканчивается после выполнения scripts.php. При вызове функции все созданные в ней переменные являются локальными по умочанию. И при выходе из функции должны удаляться. — В теории.

Похоже, это действительно работает ТОЛЬКО в теории
После использования этого метода — сразу полезла куча варнингов с указанием на то, что очередной параметр в очередную функцию не передался (этих ф-ций у меня множество, как и модулей, в которых они содержатся). х.з. почему так, не смог разобраться. Видимо, переменные перестали быть глобальными (где они объявляны таковыми), или ещё что-то.

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

Источник

Как очистить значения всех переменных?

kimono

Подскажи, пожалуйста, нужно ли всегда чистить переменные в конце своего кода или php сам очистит себя от мусора после выполнения всего кода?

Просто был у меня однажды случай, когда сервак у меня тупо завис из-за переполнения памяти, я слишком часто обращался к своему php скрипту пока он вдруг не лег, а ведь этого по идее не должно было быть.

Надим Закиров, когда скрипт завершает работу память освобождается автоматически.
Посмотрите профайлером в какой момент у вас максимальное потребление памяти, оптимизируйте самые нагруженные участки.

Также можете прямо во время работы скрипта проверять memory_get_usage и memory_get_peak_usage
И можете узнавать сколько памяти доступно в системе https://stackoverflow.com/questions/1455379/get-se.

Stalker_RED, хммм. а может такое быть, что я прервал запрос в браузере по таймауту в 5 сек, но скрипт на сервере продолжил выполнятся и через 10 и через 15 секунд?

Надим Закиров, есть параметр ignore_user_abort, при котором выполнение на сервере будет продолжаться,
Кроме того, если сигнал со стороны браузера не пришел (обрыв связи, например), или даже не был отправлен (браузер завис, вкладка крешнуласть) то выполнение продолжится, пока не завершится по таймауту.

Stalker_RED, случаем не знаете, может есть способы ограничить время выполнения кода? Например, в одном из GET-параметров я мог бы передавать желаемый таймаут, только как бы заставить PHP скрипт работать не дольше, чем указанный мной таймаут?

Источник

PHP unset()

PHP unset()

The following article provides an outline on PHP unset(). The primary operation of the method unset() is to destroy the variable specified as an input argument for it. In other words, it performs a reset operation on the selected variable. However, its behavior can vary depending on the type of variable that is being targeted to destroy. This function is supported by version PHP4 onwards.

Читайте также:  Php функции работы с сокетами

Web development, programming languages, Software testing & others

Syntax of PHP unset()

unset(mixed $selectedvar, mixed $selectedvar1,…. mixed $selectedvarN): void
  • selectedvar: The mandatory argument for unset() method. At least one variable to unset, needs to be given as input argument for the method.
  • selectedvarN: The optional parameter which can be given as input argument, to unset() method to reset it.

Use Cases for unset()

Given below are the different cases:

1. Applying unset() for local variable

When the local variable is passed to unset function, the function resets the variable.

"; unset($input); //Applying unset() method on $input variable echo "The value of 'input' after unset: " . $input; ?>

The value contained in the variable ‘input’ is destroyed on execution of the unset() method.

php unset() 1

2. Applying unset for variable inside a function which is global variable

When user attempts to use Unset for a variable within a function and it is also defined as global variable, then unset() resets only the local one. The global one remains unaffected.

"; global $Avariable; unset($Avariable); //Deletes the local ‘Avariable’ echo "Within the function scope after unset: ".$Avariable."
"; > $Avariable = 'Global Value'; //The global ‘Avariable’ echo "Out of the function scope before unset: ".$Avariable."
"; Afunction(); echo "Out of the function scope after unset: ".$Avariable."
"; ?>

The local version of the variable ‘Avariable’ is destroyed where as the global version remains intact.

php unset() 2

3. Applying unset for global variable within a function

If the variable within the function is also declared as global variable and user needs to destroy the global one, then it can be achieved using the array[$GLOBAL].

"; global $Avariable; unset($GLOBALS['Avariable']); //Resets the global ‘Avariable’ echo "Within the function scope after unset: ".$Avariable."
"; > $Avariable = 'Global Value'; echo "Out of the function scope before unset: ".$Avariable."
"; Afunction(); echo "Out of the function scope after unset: ".$Avariable."
"; ?>

The local version of the variable ‘Avariable’ is not affected by the execution of the unset function whereas the global version of the variable is set to null value.

php unset() 3

4. Applying unset() for pass by reference variable

If unset() is called on a variable that is passed to the function as reference, unset() resets only the local one. The variable instance in the calling environment retains as it is.

"; unset($Avariable); //Resets the local ‘Avariable’ echo "Within the function scope after unset: ".$Avariable."
"; > $Avariable = 'External Value'; echo "Out of the function scope before unset: ".$Avariable."
"; Afunction($Avariable); echo "Out of the function scope after unset: ".$Avariable."
"; ?>

The unset() method called in the pass by reference variable ‘Avariable’ resets only the content of the variable in the local scope without affecting the content from the external scope.

Читайте также:  Python read file argv

variable instance in the calling environment retains

5. Applying unset() for static variable

When a static variable is set as input argument to unset() method, the variable gets reset for the remaining command in the function scope after the function unset() is called.

"; //Deletes ‘staticvar’ only for the below commands within the scope of this ‘UnsetStatic’ function unset($staticvar); echo "after unset() method is called: $staticvar"."
"; > UnsetStatic(); UnsetStatic(); UnsetStatic(); ?>

The variable ‘staticvar’ is reset only for the commands followed after unset() method is called.

variable gets reset for the remaining command

6. Applying unset() on an array element

The application of unset() method on an array element deletes the element from the array without exhibiting re-indexing operation.

 "first", 1 => "second", 2 => "third"]; Echo "The array elements, before unset:"."
"; Echo $arrayinput[0]." ". $arrayinput[1]." ". $arrayinput[2]." "."
"; //Unset operation is called on the second element of the array ‘arrayinput’ unset($arrayinput[1]); Echo "The array elements, after unset:"."
"; Echo $arrayinput[0]." ". $arrayinput[1]." ". $arrayinput[2]." "; ?>

deletes the element from the array without exhibiting

7. Applying unset() on more than one element at a time

The unset() method supports deleting multiple variable at once.

"; echo "The value of 'input2' before unset: " . $input2 . "
"; echo "The value of 'input3' before unset: " . $input3 . "
"; echo "
"; //Reseting input1, input2 and input3 together in single command unset($input1,$input2,$input3); echo "The value of 'input1' after unset: " . $input1."
"; echo "The value of 'input2' after unset: " . $input2."
"; echo "The value of 'input3' after unset: " . $input3."
"; ?>

supports deleting multiple variable at once

Note: (unset) casting is not same as the function unset(). (unset)casting is used only as cast of type NULL whereas unset() method alters the variable. unset() is a language construct and hence is not supported by variable function. unset() method can be used to reset object properties that are visible in the current scope except ‘$this’ variable within any object method. In order to perform unset operation on the object properties that are not accessible in the current scope, an overloading method __unset() needs to be declared and called.

This is a guide to PHP unset(). Here we discuss the introduction to use cases for unset() along with examples for better understanding. You may also have a look at the following articles to learn more –

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

Оцените статью