CakeFest 2024: The Official CakePHP Conference

İsim alanlarının kullanımı: son çare olarak küresel işlev ve sabitler

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Bir isim alanı içinde PHP, bir sınıf ismi, işlev veya sabitin bağlamında nitelenmemiş isimlere rastlarsa bunları farklı önceliklerle ele alır. Sınıf isimleri daima geçerli isim alanı ismine çözümlenir. Dolayısıyla yerleşik veya isim alansız kullanıcı sınıflarına erişmek için, bunların aşağıdaki gibi tamamen nitelenmiş isimlerinin kullanılması gerekir:

Örnek 1 - Küresel sınıflara bir isim alanı içinde erişim

<?php
namespace A\B\C;
class
Exception extends \Exception {}

$a = new Exception('hi'); // $a, A\B\C\Exception sınıfının bir nesnesidir
$b = new \Exception('hi'); // $b, Exception sınıfının bir nesnesidir

$c = new ArrayObject; // ölümcül hata, A\B\C\ArrayObject yoktur
?>

İşlevler ve sabitler açısından PHP, bir isim alanlı işlev veya sabit mevcut değilse son çare olarak küresel işlevlere ve sabitlere başvurur.

Örnek 2 - Bir isim alanı içinde son çare olarak küresel işlev ve sabitlerin kullanımı

<?php
namespace A\B\C;

const
E_ERROR = 45;
function
strlen($str)
{
return
\strlen($str) - 1;
}

echo
E_ERROR, "\n"; // "45" basar
echo INI_ALL, "\n"; // "7" basar - son çare olarak küresel INI_ALL

echo strlen('hi'), "\n"; // "1" basar
if (is_array('hi')) { // "dizi değil" basar
echo "dizi\n";
} else {
echo
"dizi değil\n";
}
?>

add a note

User Contributed Notes 1 note

up
35
markus at malkusch dot de
9 years ago
You can use the fallback policy to provide mocks for built-in functions like time(). You therefore have to call those functions unqualified:

<?php
namespace foo;

function
time() {
return
1234;
}

assert (1234 == time());
?>

However there's a restriction that you have to define the mock function before the first usage in the tested class method. This is documented in Bug #68541.

You can find the mock library php-mock at GitHub.
To Top