Longhorn PHP 2023 - Call for Papers

assert

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

assertSavın doğruluğuna bakar

Açıklama

PHP 5 ve 7

assert(mixed $sav, string $açıklama = ?): bool

PHP 7

assert(mixed $sav, Throwable $açıklama = ?): bool

assert() işlevi belirtilen savın doğruluğuna bakar ve sonuç false ise uygun eylemi devreye sokar.

Geleneksel savlar (PHP 5 ve 7)

sav bir dizge olarak verilirse, assert() tarafından PHP kodu olarak değerlendirilir. sav olarak mantıksal bir koşul belirtilirse, bu koşul, assert_options() ile tanımlanan sav işlevine boş dizge olarak aktarılır.

Savlar yalnızca hata ayıklama özelliği olarak kullanılmalıdır. Bunlar, her zaman true olması gereken ve değilse bazı yazılım hatalarını gösteren koşulları veya eklenti işlevleri, belirli sistem sınırları ve özellikleri gibi belirli özelliklerin varlığını sınamak için kullanılabilir.

Savlar, girdi bağımsız değişkeni sınamaları gibi normal çalışma zamanı işlemleri için kullanılmamalıdır. Genel bir kural olarak, sav sınaması etkinleştirilmemiş olsa bile kodunuz her zaman doğru şekilde çalışabilmelidir.

assert() işlevinin davranışı, assert_options() ile veya bu işlevlerin kılavuz sayfalarında açıklanan .ini ayarları kullanılarak yapılandırılabilir.

assert_options() işlevi ve/veya ASSERT_CALLBACK yapılandırma yönergesi, başarısız savları işlemek için bir geri çağırım işlevinin tanımlanmasını sağlar.

assert() geri çağırımları, otomatikleştirilmiş denemeler yapmak için özellikle kullanışlıdır, çünkü sava aktarılan kod ve savın yapıldığı yer gibi bilgilerin kolayca yakalanmasına olanak tanır. Bu bilgiler başka yöntemlerle elde edilebilirse de savlar kullanılarak çok daha hızlı ve kolay hale getirilebilir!

Geri çağırım işlevinin üç bağımsız değişken kabul etmesi gerekir. İlk bağımsız değişken savın başarısız olduğu dosyayı, ikinci bağımsız değişken savın başarısız olduğu satırı ve üçüncü bağımsız değişken başarısız olan ifadeyi içerecektir (— karakteri varsa 1 veya "iki" gibi değişmez değerler bu bağımsız değişken ile aktarılamaz). PHP 5.4.8 ve sonraki sürümlerde ayrıca, assert() işlevine aktarılan açıklamayı içeren dördüncü bir seçimlik bağımsız değişkenin aktarımı da mümkündür.

Beklentiler (sadece PHP 7 için)

assert(), PHP 7'de beklentilerin tanımlanmasına izin veren bir dil yapısıdır: geliştirme ve deneme ortamlarında etkili olan, ancak üretimdeki maliyeti sıfır olacak şekilde en iyilenmiş savlar.

assert_options() geriye uyumluluk nedenleriyle yukarıda açıklandığı gibi davranışı denetim altında tutmak için kullanılabilirken, PHP 7'ye özgü kod, assert() işlevinin davranışını denetlemek için aşağıdaki iki yeni yapılandırma yönergesini kullanmalı ve assert_options() işlevini çağırMAmalıdır.

assert() için PHP 7 yapılandırma yönergeleri
Yönerge Öntanımlı değer Olası değerler
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.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)

Bağımsız Değişkenler

sav

PHP 5'te, bu değerlendirilecek bir dizge veya sınanacak mantıksal bir ifade, PHP 7'de, ayrıca, çalıştırılacak ve sonucu, savın başarının belirlemekte kullanılacak değeri döndüren bir ifade olmalıdır.

Uyarı

PHP 7.2 ve sonrasında, sav olarak dizge kullanımı artık ÖNERİLMEMEKTE olup PHP 8.0.0'da kullanımdan KALDIRILMIŞTIR.

açıklama

sav başarısız olursa başarısızlık iletisine dahil edilecek isteğe bağlı bir açıklama. PHP 7'den itibaren, bir açıklama belirtilmemişse, assert() çağrısı için kaynak koduna eşit bir öntanımlı açıklama sağlanır.

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 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.
7.0.0 assert() artık bir işlev değil bir dil oluşumu. sav artık bir ifade olabiliyor. İkinci bağımsız değişken ya bir istisna (bir Throwable nesnesi belirtilmişse), ya da 5.4.8 sürümünden beri desteklendiği gibi bir açıklama olabiliyor.

Örnekler

- Geleneksel savlar (PHP 5 ve 7)

Örnek 1 - Başarısız savın özel bir işleyici ile ele alınması

<?php
// Savı etkinleştir ve sessizleştir
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// İşleyici işlevi oluştur
function my_assert_handler($file, $line, $code)
{
echo
"<hr>Sav başarısız:
Dosya '
$file'<br />
Satır '
$line'<br />
Kod '
$code'<br /><hr />";
}

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

// Başarısız bir sav
assert('mysql_query("")');
?>

Örnek 2 - Bir açıklama göstermek için özel işleyici kullanımı

<?php
// Savı etkinleştir ve sessizleştir
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// İşleyici işlevi oluştur
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şlevini kaydet
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

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

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

Sav başarısız - test.php:21: 2 < 1
Sav başarısız - test.php:22: 2 < 1: İki birden küçüktür
 

- Beklentiler (sadece PHP 7 için)

Örnek 3 - Ö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 4 - Ö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

Ayrıca Bakınız

add a note

User Contributed Notes 9 notes

up
26
hodgman at ali dot com dot au
14 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
16 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
6 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
12 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
9 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