PHP.mk документација

class_alias

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.class-alias.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.class-alias.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
class_alias

Референца за `function.class-alias.php` со подобрена типографија и навигација.

function.class-alias.php

class_alias

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

class_aliasКреира носец (alias) за класа

= NULL

class_alias(string $class, string $alias, bool $autoload = true): bool

Креира носец именуван alias врз основа на класа дефинирана од корисникот class. Носецот (aliased class) е идентичен со оригиналната класа.

Забелешка: Од PHP 8.3.0, class_alias() исто така поддржува креирање на носец за внатрешна PHP класа.

Параметри

class

Оригиналната класа.

alias

Името на носецот за класата.

autoload

Дали да autoload ако оригиналната класа не е пронајдена.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Дневник на промени

Верзија = NULL
8.3.0 class_alias() сега поддржува креирање на носец за внатрешна класа.

Примери

Пример #1 class_alias() example

<?php

class Foo { }

class_alias('Foo', 'Bar');

$a = new Foo;
$b = new Bar;

// the objects are the same
var_dump($a == $b, $a === $b);
var_dump($a instanceof $b);

// the classes are the same
var_dump($a instanceof Foo);
var_dump($a instanceof Bar);

var_dump($b instanceof Foo);
var_dump($b instanceof Bar);

?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

Белешки

Забелешка:

Имињата на класите не прават разлика помеѓу големи и мали букви во PHP, и ова се рефлектира во оваа функција. Носеците креирани од class_alias() се декларираат со мали букви. Ова значи дека за класа MyClassсимболот, на пр. class_alias('MyClass', 'MyClassAlias') повикот ќе декларира нов носец за класа именуван myclassalias.

Види Исто така

  • get_parent_class() - Презема име на родителска класа за објект или класа
  • is_subclass_of() - Проверува дали објектот ја има оваа класа како еден од своите родители или ја имплементира

Белешки од корисници 14 белешки

mweierophinney на gmail точка com
пред 13 години
class_alias() gives you the ability to do conditional imports.

Whereas the following will not work:

<?php
namespace Component;

if (version_compare(PHP_VERSION, '5.4.0', 'gte')) {
    use My\ArrayObject;
} else {
    use ArrayObject;
}

class Container extends ArrayObject
{
}
?>

the following, using class_alias, will:

<?php
namespace Component;

if (version_compare(PHP_VERSION, '5.4.0', 'lt')) {
    class_alias('My\ArrayObject', 'Component\ArrayObject');
} else {
    class_alias('ArrayObject', 'Component\ArrayObject');
}

class Container extends ArrayObject
{
}
?>

The semantics are slightly different (I'm now indicating that Container extends from an ArrayObject implementation in the same namespace), but the overall idea is the same: conditional imports.
robsonvnasc на gmail точка com
пред 9 години
It also works with Traits!

<?php 
trait Foo {}
class_alias("Foo","Bar");
echo trait_exists("Bar") ? 'yes' : 'no'; 
?>
//yes
programmer-comfreek на hotmail точка com
пред 14 години
If you defined the class 'original' in a namespace, you will have to specify the namespace(s), too:
<?php
namespace ns1\ns2\ns3;

class A {}

class_alias('ns1\ns2\ns3\A', 'B');
/* or if you want B to exist in ns1\ns2\ns3 */
class_alias('ns1\ns2\ns3\A', 'ns1\ns2\ns3\B');
?>
nicolas точка grekas+php на gmail точка com
пред 15 години
class_alias also works for interfaces!

<?php
interface foo {}
class_alias('foo', 'bar');
echo interface_exists('bar') ? 'yes!' : 'no'; // prints yes!
?>
elliseproduction на gmail точка com
пред 5 години
You can add a alias inside a class :

<?php

class foo{

    function __construct(){
        
        echo('yes!');
    
    }
}

class bar {

    function __construct(){
        
        class_alias('foo', 'fooAlias');
    
    }
    
    function test(){
        
        new fooAlias;
        
    }

}

$bar=new bar;

$bar->test(); // yes!
randolphothegreat at yahoo dot com
пред 10 години
class_alias() creates aliases only for user defined classes, not for classes supplied by PHP (PHP will show the warning "First argument of class_alias() must be a name of user defined class"). To create aliases for every kind of classes, use namespaces:

<?php

// Does not work
class_alias("ZipArchive", "myZip");

// Creates class alias "myZip" of class "ZipArchive"
use \ZipArchive as myZip;

?>
Хејли Вотсон
пред 7 години
The alias really is an alias for the existing class. It's not a new class of any kind - whether by inheritance or otherwise; it doesn't just look and behave exactly like the existing class; it really is the same class.

<?php

class foo
{
    public static $count = 0;
}

class_alias('foo', 'bar');

bar::$count++;

echo foo::$count; // Output: 1

echo get_class(new Bar); // Output: foo
?>
Note in the last line there that aliases are just as case-insensitive as "genuine" class names.
sergey точка karavay на gmail точка com
пред 13 години
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

class_alias is NOT equivalent to class extending! Private methods/properties are unseen in child classes, but in alias classes they are.
адам на adamhahn точка com
пред 14 години
Something to note,

If the $original class has not yet been defined or loaded, the auto loader will be invoked in order to try and load it.

If the class for which you are trying to create an alias does not exist, or can not be loaded with the auto loader, you will generate a PHP Warning.
Анонимен
пред 5 години
Check is alias:
<?php
/**
 * @param string $class Class name
 * @return bool
 */
function is_alias(string $class): bool
{
    return $class !== (new ReflectionClass($class))->name;
}
?>
Get class aliases:
<?php
/**
 * @param string $class Class name
 * @param bool $throw Throw exception at error?
 * @return string[]|null Aliases or null at error in silent mode
 * @throws InvalidArgumentException Class not exists or it's alias
 */
function get_class_aliases(string $class, bool $throw = false): ?array
{
    /**
     * @var array An array of defined classes: keys - classes, values - aliases
     */
    static $classes = [];
    // check: class exists
    if (! class_exists($class, true)) {
        if ($throw) {
            throw new InvalidArgumentException('Class ' . $class . ' not exists');
        }
        return null;
    }
    // refresh list
    $newClasses = array_diff(get_declared_classes(), array_keys($classes));
    if ($newClasses) {
        $abc = range('a', 'z');
        foreach ($newClasses as $newClass) {
            // fast check first char: class_alias() convert alias to lower case
            if (in_array($newClass[0], $abc, true)) {
                $realClass = (new ReflectionClass($newClass))->getName();
                $classes[$newClass] = $newClass !== $realClass ? $realClass : null;
            } else {
                $classes[$newClass] = null;
            }
        }
        unset($abc, $newClasses);
    }
    // check: is alias?
    if (! empty($classes[$class])) {
        if ($throw) {
            throw new InvalidArgumentException($class . ' is alias for class ' . $classes[$class]);
        }
        return null;
    }
    // find aliases
    return array_keys($classes, $class, true);
}
?>
Usage:
<?php
class Foo {}
class_alias('Foo', 'Bar');
class_alias('Bar', 'Baz');
$aliases = get_class_aliases('Foo', true); // ['bar', 'baz']
?>
info на ensostudio точка ru
пред 5 години
Note: this function set alias for user classes, you can't use something like this
<?php
class_alias('ArrayObject', 'ArrObj');
?>
nicolas точка grekas+php на gmail точка com
пред 15 години
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

BUT when derivation creates a new class name - that means, you can then instantiate a new kind of objects - aliasing is just what it says: a synonym, so objects instantiated with the aliased name are of the exact same kind of objects instantiated with the non-aliased name.

See this code for example:
<?php
class A {};
class B1 extends A {};
class_alias('A', 'B2');

$b1 = new B1; echo get_class($b1); // prints B1
$b2 = new B2; echo get_class($b2); // prints A !
?>
sofe2038 на gmail точка com
пред 9 години
Doesn't work with coupled classes when used along with autoloading.

For example, in these classes where each class is autoloaded in a separate class file:

Foo.php:

<?php
interface Foo{
  public function fx(Bar $bar);
}
?>

Bar2.php:

<?php
class Bar2 implements Foo{
  public function fx(Bar2 $bar){
    // some implementation code here
  }
}
?>

Bar.php:

<?php
class_alias("Bar2", "Bar");
?>

When used with an autoloader like this:

<?php
spl_autoload_register(function($class){
  require($class . ".php");
});
new Bar;
?>

Results in fatal error:

    Declaration of Bar2::fx(Bar2 $bar) must be compatible with Foo::fx(Bar $bar) in ~/Bar2.php on line 2
sofe2038 на gmail точка com
пред 9 години
Doesn't work with coupled classes when used along with autoloading.

For example, in these classes where each class is autoloaded in a separate class file:

Foo.php:

<?php
interface Foo{
  public function fx(Bar $bar);
}
?>

Bar2.php:

<?php
class Bar2 implements Foo{
  public function fx(Bar2 $bar){
    // some implementation code here
  }
}
?>

Bar.php:

<?php
class_alias("Bar2", "Bar");
?>

When used with an autoloader like this:

<?php
spl_autoload_register(function($class){
  require($class . ".php");
});
new Bar;
?>

Results in fatal error:

    Declaration of Bar2::fx(Bar2 $bar) must be compatible with Foo::fx(Bar $bar) in ~/Bar2.php on line 2
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.