Использование классов внутри других классов
Бывает такое, что мы хотели бы использовать методы одного класса внутри другого, но не хотели бы наследовать от этого класса.
Почему мы не хотим наследовать?
Во-первых, используемый класс может являться вспомогательным и по логике нашего кода может не подходить на роль родителя.
Во-вторых, мы можем захотеть использовать несколько классов внутри другого класса, а с наследованием это не получится, ведь в PHP у класса может быть только один родитель.
Давайте посмотрим на практическом примере. Пусть у нас дан следующий класс Arr , в объект которого мы можем добавлять числа с помощью метода add :
Давайте теперь добавим в наш класс метод, который будет находить сумму квадратов элементов и прибавлять к ней сумму кубов элементов.
Пусть у нас уже существует класс SumHelper , имеющий методы для нахождения сумм элементов массивов:
Логично будет не реализовывать нужные нам методы еще раз в классе Arr , а воспользоваться методами класса SumHelper внутри класса Arr .
Для этого в классе Arr внутри конструктора создадим объект класса SumHelper и запишем его в свойство sumHelper :
Теперь внутри Arr доступно свойство $this->sumHelper , в котором хранится объект класса SumHelper с его публичными методами и свойствами (если бы публичные свойства были, сейчас их там нет, только публичные методы).
Создадим теперь в классе Arr метод getSum23 , который будет находить сумму квадратов элементов и прибавлять к ней сумму кубов элементов, используя методы класса SumHelper :
sumHelper = new SumHelper; > // Находим сумму квадратов и кубов элементов массива: public function getSum23() < // Для краткости запишем $this->nums в переменную: $nums = $this->nums; // Найдем описанную сумму: return $this->sumHelper->getSum2($nums) + $this->sumHelper->getSum3($nums); > public function add($number) < $this->nums[] = $number; > > ?>?php>
Давайте воспользуемся созданным классом Arr :
add(1); // добавляем в массив число 1 $arr->add(2); // добавляем в массив число 2 $arr->add(3); // добавляем в массив число 3 // Находим сумму квадратов и кубов: echo $arr->getSum23(); ?>?php>
Самостоятельно повторите описанные мною классы Arr и SumHelper .
Создайте класс AvgHelper с методом getAvg , который параметром будет принимать массив и возвращать среднее арифметическое этого массива (сумма элементов делить на количество).
Добавьте в класс AvgHelper еще и метод getMeanSquare , который параметром будет принимать массив и возвращать среднее квадратичное этого массива (квадратный корень, извлеченный из суммы квадратов элементов, деленной на количество).
Добавьте в класс Arr метод getAvgMeanSum , который будет находить сумму среднего арифметического и среднего квадратичного из массива $this->nums .
Php import class in class
The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.
PHP can alias(/import) constants, functions, classes, interfaces, traits, enums and namespaces.
Aliasing is accomplished with the use operator. Here is an example showing all 5 kinds of importing:
Example #1 importing/aliasing with the use operator
namespace foo ;
use My \ Full \ Classname as Another ;
?php
// this is the same as use My\Full\NSname as NSname
use My \ Full \ NSname ;
// importing a global class
use ArrayObject ;
// importing a function
use function My \ Full \ functionName ;
// aliasing a function
use function My \ Full \ functionName as func ;
// importing a constant
use const My \ Full \ CONSTANT ;
$obj = new namespace\ Another ; // instantiates object of class foo\Another
$obj = new Another ; // instantiates object of class My\Full\Classname
NSname \ subns \ func (); // calls function My\Full\NSname\subns\func
$a = new ArrayObject (array( 1 )); // instantiates object of class ArrayObject
// without the «use ArrayObject» we would instantiate an object of class foo\ArrayObject
func (); // calls function My\Full\functionName
echo CONSTANT ; // echoes the value of My\Full\CONSTANT
?>
Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar ), the leading backslash is unnecessary and not recommended, as import names must be fully qualified, and are not processed relative to the current namespace.
PHP additionally supports a convenience shortcut to place multiple use statements on the same line
Example #2 importing/aliasing with the use operator, multiple use statements combined
use My \ Full \ Classname as Another , My \ Full \ NSname ;
?php
$obj = new Another ; // instantiates object of class My\Full\Classname
NSname \ subns \ func (); // calls function My\Full\NSname\subns\func
?>
Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.
Example #3 Importing and dynamic names
use My \ Full \ Classname as Another , My \ Full \ NSname ;
?php
$obj = new Another ; // instantiates object of class My\Full\Classname
$a = ‘Another’ ;
$obj = new $a ; // instantiates object of class Another
?>
In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.
Example #4 Importing and fully qualified names
use My \ Full \ Classname as Another , My \ Full \ NSname ;
?php
$obj = new Another ; // instantiates object of class My\Full\Classname
$obj = new \ Another ; // instantiates object of class Another
$obj = new Another \ thing ; // instantiates object of class My\Full\Classname\thing
$obj = new \ Another \ thing ; // instantiates object of class Another\thing
?>
Scoping rules for importing
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped. The following example will show an illegal use of the use keyword:
Example #5 Illegal importing rule
function toGreenlandic ()
use Languages \ Danish ;
Note:
Importing rules are per file basis, meaning included files will NOT inherit the parent file’s importing rules.
Group use declarations
Classes, functions and constants being imported from the same namespace can be grouped together in a single use statement.
use some \namespace\ ClassA ;
use some \namespace\ ClassB ;
use some \namespace\ ClassC as C ;
use function some \namespace\ fn_a ;
use function some \namespace\ fn_b ;
use function some \namespace\ fn_c ;
use const some \namespace\ ConstA ;
use const some \namespace\ ConstB ;
use const some \namespace\ ConstC ;
// is equivalent to the following groupped use declaration
use some \namespace\< ClassA , ClassB , ClassC as C >;
use function some \namespace\< fn_a , fn_b , fn_c >;
use const some \namespace\< ConstA , ConstB , ConstC >;
Php import class in class
The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.
PHP can alias(/import) constants, functions, classes, interfaces, and namespaces.
Aliasing is accomplished with the use operator. Here is an example showing all 5 kinds of importing:
Example #1 importing/aliasing with the use operator
namespace foo ;
use My \ Full \ Classname as Another ;
?php
// this is the same as use My\Full\NSname as NSname
use My \ Full \ NSname ;
// importing a global class
use ArrayObject ;
// importing a function
use function My \ Full \ functionName ;
// aliasing a function
use function My \ Full \ functionName as func ;
// importing a constant
use const My \ Full \ CONSTANT ;
$obj = new namespace\ Another ; // instantiates object of class foo\Another
$obj = new Another ; // instantiates object of class My\Full\Classname
NSname \ subns \ func (); // calls function My\Full\NSname\subns\func
$a = new ArrayObject (array( 1 )); // instantiates object of class ArrayObject
// without the «use ArrayObject» we would instantiate an object of class foo\ArrayObject
func (); // calls function My\Full\functionName
echo CONSTANT ; // echoes the value of My\Full\CONSTANT
?>
Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar ), the leading backslash is unnecessary and not recommended, as import names must be fully qualified, and are not processed relative to the current namespace.
PHP additionally supports a convenience shortcut to place multiple use statements on the same line
Example #2 importing/aliasing with the use operator, multiple use statements combined
use My \ Full \ Classname as Another , My \ Full \ NSname ;
?php
$obj = new Another ; // instantiates object of class My\Full\Classname
NSname \ subns \ func (); // calls function My\Full\NSname\subns\func
?>
Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.
Example #3 Importing and dynamic names
use My \ Full \ Classname as Another , My \ Full \ NSname ;
?php
$obj = new Another ; // instantiates object of class My\Full\Classname
$a = ‘Another’ ;
$obj = new $a ; // instantiates object of class Another
?>
In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.
Example #4 Importing and fully qualified names
use My \ Full \ Classname as Another , My \ Full \ NSname ;
?php
$obj = new Another ; // instantiates object of class My\Full\Classname
$obj = new \ Another ; // instantiates object of class Another
$obj = new Another \ thing ; // instantiates object of class My\Full\Classname\thing
$obj = new \ Another \ thing ; // instantiates object of class Another\thing
?>
Scoping rules for importing
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped. The following example will show an illegal use of the use keyword:
Example #5 Illegal importing rule
function toGreenlandic ()
use Languages \ Danish ;
Note:
Importing rules are per file basis, meaning included files will NOT inherit the parent file’s importing rules.
Group use declarations
Classes, functions and constants being imported from the same namespace can be grouped together in a single use statement.
use some \namespace\ ClassA ;
use some \namespace\ ClassB ;
use some \namespace\ ClassC as C ;
use function some \namespace\ fn_a ;
use function some \namespace\ fn_b ;
use function some \namespace\ fn_c ;
use const some \namespace\ ConstA ;
use const some \namespace\ ConstB ;
use const some \namespace\ ConstC ;
// is equivalent to the following groupped use declaration
use some \namespace\< ClassA , ClassB , ClassC as C >;
use function some \namespace\< fn_a , fn_b , fn_c >;
use const some \namespace\< ConstA , ConstB , ConstC >;