Burada PHP bildirimin nasıl kurtulabilirsiniz?

6 Cevap php
function t1()
{
  echo 1;
}
function t2()
{ 
  echo 2;
}

$funcs = array(t1,t2);

$length = count($funcs);
for($i=0;$i<$length;$i++)
{
$funcs[$i]();
}

: Ben bu küçük php dosyayı çalıştırdığınızda

PHP Notice: tanımsız sabit t1 Kullanımı - D 't1' varsayılır: hattında 11 \ jobirn \ test \ str.php

PHP Notice: tanımsız sabit t2 Kullanımı - D 't2' varsayılır: hattında 11 \ jobirn \ test \ str.php

How can I get rid of those Notices? 12

6 Cevap

You get a notice because PHP doesn't treat functions as first class objects. When you do this

$functions = array(t1, t2);

The PHP engine sees t1, and t2, and tries to resolve it as a constant, but because it cannot find a constant named t1/t2, it "assumes" that you wanted to type array('t1', 't2'); If you do a var_dump($functions), you can see that the items in the array are strings.

Eğer gibi, bir fonksiyonu olarak bir dize aramak için çalıştığınızda

$functions[0]()

PHP dizge olarak aynı adı taşıyan bir işlev için bakacağız. Ben bir işlev işaretçisi olarak bir dize kullanarak olarak bu çağrı değildir, bu daha çok yansıma kullanmak gibidir. PHP görüyorum, "değişkenli fonksiyonlar" çağırır:

http://hu2.php.net/manual/en/functions.variable-functions.php

Yani, bildirimler kurtulmak için doğru yolu:

$functions = array('t1', 't2');

Yok neden

't1'();

çalışmıyor? Ne yazık ki hiçbir cevap yoktur. PHP var, cehennem tuhaflıklar olarak rahatsız edici bu iyi bir sayı vardır. Sanki aynı cilvesi:

explode(':', 'one:two:three')[0];
Parse error: syntax error, unexpected '[' in php shell code on line 1

Edit:
The above mentioned array referencing syntax is available in PHP5.4, it's called array dereferencing.

$funcs = array('t1','t2');

Unintuitive, ama bu nasıl çalışıyor

Bu konuya iş yuvarlak gelen php.ini ayarlarını değiştirmek için

error_reporting = E_ALL

karşı

error_reporting = E_ALL & ~E_NOTICE

Error_reporting () fonksiyonu Çıkış:

http://us2.php.net/manual/en/function.error-reporting.php

Bu görüntülenen hataları, bildirimler ve uyarılar ne düzeyde yapılandırmanızı sağlar.

Örneğin, hataları ve uyarıları ve bildirimleri hiçbir isterseniz:

error_reporting (E_ERROR | e_warning);

Kullan string declarations dizeleri demek eğer:

$funcs = array('t1','t2');

PHP kılavuzunda da chapter on varaible functions bakın.

bir işlevi çağırmak için dizeleri kullanmak üzere, kıvırcık parantez kullanmak gerekir

'hello'() // wont work
$hello = 'hello'; $hello() // will work

Düzenlemek o {''} () çalışmıyor gibi görünüyor. i> için kullanılan hatırlıyorum. <