PHP 8.1.24 Released!

assert

(PHP 4, PHP 5, PHP 7, PHP 8)

assertSavın doğruluğuna bakar

Açıklama

assert(mixed $sav, Throwable|string|null $açıklama = null): bool

assert() bir işlev değil beklentilerin tanımlanmasını sağlayan bir dil oluşumudur: geliştirme ve deneme ortamlarında yürürlüğe giren, ancak üretimde sıfır maliyetli olacak şekilde en iyilenmiş savlardır.

Savlar yalnızca hata ayıklama özelliği olarak kullanılmalıdır. Bir kullanımı, her zaman true olması gereken, aksi takdirde bazı yazılım hatalarını gösteren ön koşullar için tutarlılık denetimidir. Başka bir kullanımı ise, eklenti işlevleri veya belirli sistem sınırları ve özellikleri gibi belirli özelliklerin varlığını sınamaktır.

Sav denetimi devre dışı bırakılabilecek şekilde yapılandırılabileceğinden, girdilerin denetlenmesi gibi normal çalışma zamanı işlemleri için kullanılmamalıdır. Genel bir kural olarak, sav denetimi devre dışı bırakılsa bile kod beklendiği gibi davranmalıdır.

assert() oluşumu, sav ile belirtilen beklentinin geçerliliğini sınar.

assert() oluşumunun davranışı aşağıdaki INI ayarları ile değiştirilebilir:

Sav yapılandırma yönergeleri
İsim Öntanımlı Açıklama Sürüm Bilgisi
zend.assertions 1
  • 1: kodu üret ve çalıştır (geliştirme kipi)
  • 0: kodu üret ama çalışma anında etrafından dolaş
  • -1: kod üretme (üretim kipi)
 
assert.active true false ise, assert() beklentiyle ilgilenmez ve koşulsuz olarak true döndürür.  
assert.callback null Sav başarısız olduğunda çağrılacak kullanıcı tanımlı işlev. Sözdizimi:
assert_callback(
    string $dosya,
    int $satır,
    null $sav,
    string $açıklama = ?
): void
PHP 8.0.0 öncesnde, işlevin sözdizimi şöyle olmalıydı:
assert_callback(
    string $dosya,
    int $satır,
    string $sav,
    string $açıklama = ?
): void
assert.exception 0
  • 1: Sav başarısız olursa istisnayı yavrula: Ya istisna bağımsız değişkeni ile sağlanan nesneyi ya da bir nesne sağlanmamışsa AssertionError nesnesini.
  • 0: Yukarıda açıklandığı gibi bir Throwable kullan veya oluştur, ancak o nesneyi örnekllemek yerine nesneyi temel alan bir uyarı oluştur (PHP 5 davranışıyla uyumlu)
 
assert.bail false true ise, beklenti karşılanmazsa PHP betiğinin yürütülmesini iptal eder.  
assert.warning true true ise, beklenti karşılanmazsa bir E_WARNING çıktılanır. Bu INI ayarı, assert.exception etkinleştirilmişse etkisizdir.  
The options starting with assert.ile başlayan seçenekler assert_options() ile yapıaldırılabilir. Ancak, bu önerilmez.

Bağımsız Değişkenler

sav

Çalıştırılacak ve sonucu, savın başarını belirlemekte kullanılacak değeri döndüren bir ifade olmalıdır.

Uyarı

PHP 8.0.0 öncesinde, sav PHP kodu olarak yorumlanan ve eval() ile yürütülen bir dizge idi. Bu dizge geri çağırım işlevine üçüncü bağımsız değişken olarak aktarılırdı. PHP 7.2.0'da kullanımı artık ÖNERİLMEMEKTE olup PHP 8.0.0'da kullanımdan KALDIRILMIŞTIR.

açıklama

açıklama bir Throwable örneği ise, yalnızca sav yürütülüp başarısız olduğunda yavrulanır.

Bilginize:

PHP 8.0.0 ve sonrasında, bu, olası bir tanımlanmış onaylama geri çağrım işlevi çağrılmadan önce yapılır.

Bilginize:

PHP 8.0.0 ve sonrasında, nesne assert.exception yapılandırmasına bakılmaksızın yavrulanır.

Bilginize:

PHP 8.0.0 ve sonrasında, bu durumda assert.bail etkisizdir.

sav başarısız olursa başarısızlık iletisine dahil edilecek isteğe bağlı bir açıklama. açıklama bir dizge ise bir istisna veya uyarı çıktılanırsa kullanılır.

açıklama kullanılmazsa, derleme zamanında assert() çağrısı için kaynak koduna eşit öntanımlı bir açıklama oluşturulur.

istisna

PHP 7'de, ikinci bağımsız değişken açıklayıcı bir dizge yerine bir Throwable nesnesi olabilir; sav başarısız olursa ve assert.exception yapılandırma yönergesi de etkinse bu nesne örneklenir.

Dönen Değerler

sav başarısız olursa false olmazsa true döner.

Sürüm Bilgisi

Sürüm: Açıklama
8.0.0 açıklama bir Throwable örneği ise, yalnızca sav yürütülüp başarısız olduğunda yavrulanır.
8.0.0 açıklama bir Throwable örneği ise, atanmış olsa bile geri çağırım işlevi çağrılmaz.
8.0.0 assert() artık dizge savları değerlendirmeye almıyor, herhangi bir bağımsız değişken gibi ele alıyor. Örneğin, assert('$a == $b') yerine artık assert($a == $b) kullanılması gerekiyor. assert.quiet_eval php.ini yönergesi ve ASSERT_QUIET_EVAL sabiti de kaldırıldı ve artık herhangi bir etkisi olmayacak.
8.0.0 Bir isim alanı içinde assert() adlı bir işlevin bildirilmesine artık izin verilmiyor ve böyle bir bildirim olursa E_COMPILE_ERROR çıktılanıyor.
7.3.0 Bir isim alanı içinde assert() adlı bir işlev bildirimi artık önerilmiyor ve böyle bir bildirim olursa bir E_DEPRECATED uyarısı veriliyor.
7.2.0 Sav olarak bir dizge kullanımı artık önerilmiyor. Artık hem assert.active hem de zend.assertions için 1 atanmışsa bir E_DEPRECATED uyarısı veriliyor.

Örnekler

- Beklentiler

Örnek 1 - Özel bir sav olmaksızın beklentiler

<?php
assert
(true == false);
echo
'Hi!';
?>

zend.assertions yönergesine 0 atandığında yukarıdaki örneğin çıktısı:

Hi!

zend.assertions yönergesine 1 ve assert.exception yönergesine 0 atandığında yukarıdaki örneğin çıktısı:

Warning: assert(): assert(true == false) failed in - on line 2
Hi!

zend.assertions yönergesine 1 ve assert.exception yönergesine 1 atandığında yukarıdaki örneğin çıktısı:

Fatal error: Uncaught AssertionError: assert(true == false) in -:2
Stack trace:
#0 -(2): assert(false, 'assert(true == ...')
#1 {main}
  thrown in - on line 2

Örnek 2 - Özel bir sav varken beklentiler

<?php
class CustomError extends AssertionError {}

assert(true == false, new CustomError('True is not false!'));
echo
'Hi!';
?>

zend.assertions yönergesine 0 atandığında yukarıdaki örneğin çıktısı:

Hi!

zend.assertions yönergesine 1 ve assert.exception yönergesine 0 atandığında yukarıdaki örneğin çıktısı:

Warning: assert(): CustomError: True is not false! in -:4
Stack trace:
#0 {main} failed in - on line 4
Hi!

zend.assertions yönergesine 1 ve assert.exception yönergesine 1 atandığında yukarıdaki örneğin çıktısı:

Fatal error: Uncaught CustomError: True is not false! in -:4
Stack trace:
#0 {main}
  thrown in - on line 4

- Değerlendirilen kod savları (yalnızca, PHP 7)

Değerlendirilen kod savları ile, assert() geri çağırımları savın nerede yapıldığına dair bilgilerin yanı sıra sav için kullanılan kod da geri çağırıma iletildiğinden özellikle yararlı olabilir.

Örnek 3 - Başarısız bir savın özel bir işleyici ile işlenmesi

<?php
// savı etkin ve sessiz yap
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// İşleyici işlev
function my_assert_handler($file, $line, $code)
{
echo
"<hr>Assertion Failed:
File '
$file'<br />
Line '
$line'<br />
Code '
$code'<br /><hr />";
}

// geri çağırım işlevi
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Başarısız olması gereken savı öne sür
$array = [];
assert('count($array);');
?>

Yukarıdaki örneğin PHP 7.2 çıktısı::

Deprecated: assert(): Calling assert() with a string argument is deprecated in test.php on line 21
<hr>Assertion Failed:
        File 'test.php'<br />
        Line '21'<br />
        Code 'count($array);'<br /><hr />

Yukarıdaki örneğin PHP 7.1 çıktısı:

<hr>Assertion Failed:
        File 'test.php'<br />
        Line '21'<br />
        Code 'count($array);'<br /><hr />

Örnek 4 - Açıklama basmak için özel işleyici kullanımı

<?php
// savı etkin ve sessiz yap
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// İşleyici işlev
function my_assert_handler($file, $line, $code, $desc = null)
{
echo
"sav başarısız - $file:$line: $code";
if (
$desc) {
echo
": $desc";
}
echo
"\n";
}

// Geri çağırım işlevi
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Başarısız olması gereken savı öne sür
assert('2 < 1');
assert('2 < 1', 'İki birden küçüktür');
?>

Yukarıdaki örneğin PHP 7.2 çıktısı::

Deprecated: assert(): Calling assert() with a string argument is deprecated in test.php on line 21
Assertion failed at test.php:21: 2 < 1

Deprecated: assert(): Calling assert() with a string argument is deprecated in test.php on line 22
Assertion failed at test.php:22: 2 < 1: İki birden küçüktür

Yukarıdaki örneğin PHP 7.1 çıktısı:

Assertion failed at test.php:21: 2 < 1
Assertion failed at test.php:22: 2 < 1: İki birden küçüktür

Ayrıca Bakınız

add a note

User Contributed Notes 9 notes

up
26
hodgman at ali dot com dot au
15 years ago
As noted on Wikipedia - "assertions are primarily a development tool, they are often disabled when a program is released to the public." and "Assertions should be used to document logically impossible situations and discover programming errors— if the 'impossible' occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is usually unwise: assertions do not allow for graceful recovery from errors, and an assertion failure will often halt the program's execution abruptly. Assertions also do not display a user-friendly error message."

This means that the advice given by "gk at proliberty dot com" to force assertions to be enabled, even when they have been disabled manually, goes against best practices of only using them as a development tool.
up
4
Tom
3 years ago
When migrating older code to PHP 7.2+, you may get E_DEPRECATED warnings for every call to assert() you ever wrote, urging you to not pass the assertion as a string.

It may be tempting to just run a regular expression across your files to convert all strings within "assert(...)" to statements. But, before you do that, be aware of the following caveat!

For example, this code simply asserts that $input is not empty.

assert('$input;');

This works, because the string passed to assert() is evaluated as a PHP statement and the result cast to Boolean.

If you want to have an equivalent statement that doesn't pass the first parameter as a string, your regular expression should rewrite this statement as:

assert((bool) ($input));

However, this looks a bit bulky and it is tempting to instead opt for the more direct approach to convert the above line to this:

assert($input);

But! This new statement will do one of three things:

1) Looks as if it worked as intended because $input just happens to be Boolean to begin with
2) Throw a parse error if $input is a string (best case)
3) Allow an attacker on a poorly configured server to execute arbitrary PHP-Code (worst case)

The reason is that, even though on PHP 7.2+ a E_DEPRECATED warning is raised, if assert() finds the first parameter to be a string, it will still execute it as PHP-Code, just as if it was called with a string to begin with.

If an attacker finds a way to manipulate the contents of $input, you might end up with a remote code execution vulnerability. So just be extra careful when migrating assertions.
up
6
mail<at>aaron-mueller.de
17 years ago
Here is a simple demonstration of Design By Contract with PHP

<?php

assert_options
(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 1);
assert_options(ASSERT_CALLBACK, 'dcb_callback');

function
dcb_callback($script, $line, $message) {
echo
"<h1>Condition failed!</h1><br />
Script: <strong>
$script</strong><br />
Line: <strong>
$line</strong><br />
Condition: <br /><pre>
$message</pre>";
}

// Parameters
$a = 5;
$b = 'Simple DCB with PHP';

// Pre-Condition
assert('
is_integer($a) &&
($a > 0) &&
($a < 20) &&

is_string($b) &&
(strlen($b) > 5);
'
);

// Function
function combine($a, $b) {
return
"Kombined: " . $b . $a;
}

$result = combine($a, $b);

// Post-Condition
assert('
is_string($result) &&
(strlen($result) > 0);
'
);

// All right, the Function works fine
var_dump($result);

?>
up
4
Krzysztof &#39;ChanibaL&#39; Bociurko
15 years ago
Note that func_get_args() should be used carefully and never in a string! For example:

<?php
function asserted_normal($a, $b) {
assert(var_dump(func_get_args()));
}
function
asserted_string($a, $b) {
assert('var_dump(func_get_args())');
}
?>

<?php asserted_normal(1,2) ?> prints
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}

but <?php asserted_string(3,4) ?> prints
array(1) {
[0]=>
string(25) "var_dump(func_get_args())"
}

This is because of that the string passed to assert() is being evaled inside assert, and not your function. Also, note that this works correctly, because of the eval scope:

<?php
function asserted_evaled_string($a, $b) {
assert(eval('var_dump(func_get_args())'));
}
asserted_evaled_string(5,6);
?>
array(2) {
[0]=>
int(5)
[1]=>
int(6)
}

(oh, and for simplicity's sake the evaled code doesn't return true, so don't worry that it fails assertion...)
up
1
Julien MOREAU aka PixEye
1 year ago
In order to change zend.assertions or assert.exception values, try with the ini_set() function but be aware that it may fail.

Example:
<?php
$ret
= @ini_set('zend.assertions', '1');
if (
$ret === false) echo 'ini_set() failed before line ', __LINE__, PHP_EOL;
up
-2
jason at jaypha dot com
5 years ago
You can take advantage of how assert is handled to use it for crude conditional compilation.

For example

<?php
assert
(print("Some debug message\n"));
assert(($val = "dev") || true);
?>

Since print() always returns 1, the topmost assertion will pass. For others, you may need to add a || true. Always enclose the expression in ().

In a development environment where zend.assertions=1, the above code will execute. In production environments where zend.assertions=-1, it wont even compile, thus not burdening performance.

Another, more real world, example.

<?php
$cssSrc
= 'https://code.jquery.com/jquery-3.2.1.min.js';
assert(($cssSrc = 'http://dev.local/jquery-3.2.1.js') || true);
echo
"<link rel='stylesheet' type='text/css' href='$cssSrc'/>\n";
?>

In a production environment, The website will use the minified version from the CDN. In a development environment, a development version, sourced locally, will be used instead.

Note: This will not work for everything. Only code that can be embedded in an expression will work.
up
-2
Ben
7 years ago
if there was no 'warning' message when assertion failed (FALSE), try reset the error handler:
<?php
set_error_handler
( null );
up
-5
uramihsayibok, gmail, com
13 years ago
There's a nice advantage to giving assert() some code to execute, as a string, rather than a simple true/false value: commenting.

<?php

assert
('is_int($int) /* $int parameter must be an int, not just numeric */');

// and my personal favorite
assert('false /* not yet implemented */');

?>

The comment will show up in the output (or in your assertion handler) and doesn't require someone debugging to go through your code trying to figure out why the assertion happened. That's no excuse to not comment your code, of course.

You need to use a block comment (/*...*/) because a line comment (//...) creates an "unexpected $end" parse error in the evaluated code. Bug? Could be.
(You can get around it with "false // not yet implemented\n" but that screws up the message)
up
-8
office dot stojmenovic at gmail dot com
10 years ago
Example from Ikac Framework how they use assert()

<?php

/**
* Set Assertion Debug
*
* This method will check the given assertion and take appropriate -
* action if its result is FALSE.
*
* This file is part of Ikac Framework.
*
* @package Ikac Framework
* @author Ivan Stojmenovic Ikac <contact.@stojmenovic.info>
*
* @param mixed $assertion The assertion.
* @param mixed $callback Callback to call on failed assertions
* @param array $options Set the various control options or just query their current settings.
* @param string $description An optional description that will be included in the failure message if the assertion fails.
*/
public function setAssertionDebug($assertion, $callback, array $options, $description = null)
{
if (
is_array($options)) {
foreach (
$options AS $option => $value) {
assert_options($option, $value);
}
}
if (
$callback) {
assert_options(ASSERT_CALLBACK, $callback);
}

return
assert($assertion, $description);
}
?>

How to use:

<?php
use Ikac\Component\SystemBehaviour\OptionsInfo;

$system = new OptionsInfo();

$option = array(ASSERT_ACTIVE => 1,ASSERT_WARNING => 0,ASSERT_QUIET_EVAL => 1);

$system->setAssertionDebug('2<1', function(){
echo
"Assertion failed";
},
$option);

?>
To Top