php static class in class

When to use static classes in PHP? [duplicate]

I’m having a little trouble understanding the advantages/disadvantages of static vs «normal» classes in PHP, since it seems that I’m able to do the same thing with both.

If I’m able to have static variables in classes and get/modify them easily with static methods, why do I even need class instances?

4 Answers 4

Are you sure you don’t mean abstract class? PHP has abstract classes and static methods.

An abstract class provides you with a mechanism to build an object with a generalized API that can be specialized to various other objects that are subclasses of it, but for which it doesn’t make sense for an instance of the generalized class to exist. For example, if you were constructing a system that managed animals, then you may have classes for specific animals such as meerkat, ferret, gecko, snake, fish and so on. Some of the animals in the system can be grouped together by common characteristics. For example, all the animals mentioned are vertebrate, so you might have a vertebrate class which describes the characteristics common to all the animals that can be categorized as a vertebrate.

However, there is no such animal as a vertebrate, so you shouldn’t be able to have an instance of the Vertebrate class. You can have instances of ferrets and snakes, and those instances should have all the characteristics of vertebrates but a vertebrate instance would make no sense. You can further subclass of course, you might have a mammal and a reptile class which sit between vertebrate and the specific animals, but which are also abstract and cannot have instances.

Basically, you should think of an abstract class as a way of defining the general behaviour of a class of objects that might be derived from it.

Sorry if I’ve not explained myself very well, it’s a much simpler concept to understand than it is to explain.

If, on the other hand, you’re talking about classes that contain nothing but static methods, then that’s simply a way for a programmer to delude himself into believing that the procedural code he’s writing is «object oriented programming». It’s not, it’s just a way of disguising procedural programming.

There are schools of thought that frown on static methods as they can make testing sections of code in isolation very difficult. While they do have their uses, it’s generally advisable to avoid static methods.

Источник

Can I instantiate a PHP class inside another class?

I was wondering if it is allowed to create an instance of a class inside another class.

Or, do I have to create it outside and then pass it in through the constructor? But then I would have created it without knowing if I would need it.

Example (a database class):

php static class in class. Смотреть фото php static class in class. Смотреть картинку php static class in class. Картинка про php static class in class. Фото php static class in class

8 Answers 8

php static class in class. Смотреть фото php static class in class. Смотреть картинку php static class in class. Картинка про php static class in class. Фото php static class in class

People saying that it is possible to ‘create a class within a class’ seem to mean that it is possible to create an object / instance within a class. I have not seen an example of an actual class definition within another class definition, which would look like:

Since the question was ‘is it possible to create a class inside another class’, I can now only assume that it is NOT possible.

I just wanted to point out that it is possible to load a class definition dynamically inside another class definition.

Lukas is right that we cannot define a class inside another class, but we can include() or require() them dynamically, since every functions and classes defined in the included file will have a global scope. If you need to load a class or function dynamically, simply include the files in one of the class’ functions. You can do this:

It’s impossible to create a class in another class in PHP. Creating an object(an instance of a class) in another object is a different thing.

No, it is not possible. Nesting classes and aggregating objects are diffrent mechanisms. Nesting classes means nesting class names, in fact. Class A nested in class B would be named «B\A» (?). From v5.3 you can nest class names (and some other names) in namespaces.

php static class in class. Смотреть фото php static class in class. Смотреть картинку php static class in class. Картинка про php static class in class. Фото php static class in class

This is possible in PHP 7 with Anonymous classes.

See the example from the docs:

This is a simple example showing usage of anonymous classes, but not from within a class:

(Edit) Ok the question and the example of what you are trying to accomplish are confusing. It seems from your example you are trying to DEFINE a class inside another class.

The correct name for this is NESTED CLASS and it is not possible in PHP. So, to your example the answer is «NO». Not in PHP anyway. Other languages will allow «nested classes». Java is an example.

For example this will NOT work in PHP

Now the question asked is to create AN INSTANCE of a class in another class.

To this the answer is «YES», you can INSTANTIATE an «object» inside a «class». We do it all the time.

A class can even instantiate itself. That’s what the famous singleton does and many other Creational patterns. Sadly some people believe that knowing about dependency injection means they will never call NEW in a method again. WRONG.

It helps to understand the difference between a class and an object. A class is an extensible program-code-template for creating objects. An object refers to a particular instance of a class.

Источник

Готовимся к собеседованию по PHP: ключевое слово «static»

Не секрет, что на собеседованиях любят задавать каверзные вопросы. Не всегда адекватные, не всегда имеющие отношение к реальности, но факт остается фактом — задают. Конечно, вопрос вопросу рознь, и иногда вопрос, на первый взгляд кажущийся вам дурацким, на самом деле направлен на проверку того, насколько хорошо вы знаете язык, на котором пишете.

php static class in class. Смотреть фото php static class in class. Смотреть картинку php static class in class. Картинка про php static class in class. Фото php static class in class

Попробуем разобрать «по косточкам» один из таких вопросов — что значит слово «static» в PHP и зачем оно применяется?

Ключевое слово static имеет в PHP три различных значения. Разберем их в хронологическом порядке, как они появлялись в языке.

Значение первое — статическая локальная переменная

Однако всё меняется, если мы перед присваиванием поставим ключевое слово static:

Подводные камни статических переменных

Разумеется, как всегда в PHP, не обходится без «подводных камней».

Камень первый — статической переменной присваивать можно только константы или константные выражения. Вот такой код:

с неизбежностью приведет к ошибке парсера. К счастью, начиная с версии 5.6 стало допустимым присвоение не только констант, но и константных выражений (например — «1+2» или «[1, 2, 3]»), то есть таких выражений, которые не зависят от другого кода и могут быть вычислены на этапе компиляции

Камень второй — методы существуют в единственном экземпляре.
Тут всё чуть сложнее. Для понимания сути приведу код:

Такое поведение может быть неожиданным для неподготовленного к нему разработчика и послужить источником ошибок. Нужно заметить, что наследование класса (и метода) приводит к тому, что всё-таки создается новый метод:

Вывод: динамические методы в PHP существуют в контексте классов, а не объектов. И только лишь в рантайме происходит подстановка «$this = текущий_объект»

Значение второе — статические свойства и методы классов

В объектной модели PHP существует возможность задавать свойства и методы не только для объектов — экземпляров класса, но и для класса в целом. Для этого тоже служит ключевое слово static:

Для доступа к таким свойствам и методам используются конструкции с двойным двоеточием («Paamayim Nekudotayim»), такие как ИМЯ_КЛАССА::$имяПеременной и ИМЯ_КЛАССА:: имяМетода().

Само собой разумеется, что у статических свойств и статических методов есть свои особенности и свои «подводные камни», которые нужно знать.

Особенность вторая — static не аксиома!

Обратное не совсем верно:

И кстати, всё написанное выше относится только к методам. Использование статического свойства через «->» невозможно и ведет к фатальной ошибке.

Значение третье, кажущееся самым сложным — позднее статическое связывание

Разработчики языка PHP не остановились на двух значениях ключевого слова «static» и в версии 5.3 добавили еще одну «фичу» языка, которая реализована тем же самым словом! Она называется «позднее статическое связывание» или LSB (Late Static Binding).

Понять суть LSB проще всего на несложных примерах:

Ключевое слово self в PHP всегда значит «имя класса, где это слово написано». В данном случае self заменяется на класс Model, а self::$table — на Model::$table.
Такая языковая возможность называется «ранним статическим связыванием». Почему ранним? Потому что связывание self и конкретного имени класса происходит не в рантайме, а на более ранних этапах — парсинга и компиляции кода. Ну а «статическое» — потому что речь идет о статических свойствах и методах.

Немного изменим наш код:

Теперь вы понимаете, почему PHP ведёт себя в этой ситуации неинтуитивно. self был связан с классом Model тогда, когда о классе User еще ничего не было известно, поэтому и указывает на Model.

Для решения этой дилеммы был придуман механизм связывания «позднего», на этапе рантайма. Работает он очень просто — достаточно вместо слова «self» написать «static» и связь будет установлена с тем классом, который вызывает данный код, а не с тем, где он написан:

Это и есть загадочное «позднее статическое связывание».

Нужно отметить, что для большего удобства в PHP кроме слова «static» есть еще специальная функция get_called_class(), которая сообщит вам — в контексте какого класса в данный момент работает ваш код.

Источник

Php static class in class

Эта страница описывает использование ключевого слова static для определения статических методов и свойств. static также может использоваться для определения статических переменных и позднего статического связывания. Для получения информации о таком применении ключевого слова static обратитесь по вышеуказанным страницам.

Объявление свойств и методов класса статическими позволяет обращаться к ним без создания экземпляра класса. К ним также можно получить доступ статически в созданном экземпляре объекта класса.

Статические методы

Пример #1 Пример статического метода

Foo :: aStaticMethod ();
$classname = ‘Foo’ ;
$classname :: aStaticMethod ();
?>

Статические свойства

Пример #2 Пример статического свойства

Результат выполнения данного примера в PHP 8 аналогичен:

User Contributed Notes 28 notes

Here statically accessed property prefer property of the class for which it is called. Where as self keyword enforces use of current class only. Refer the below example:

public function static_test ()<

This is also possible:

You misunderstand the meaning of inheritance : there is no duplication of members when you inherit from a base class. Members are shared through inheritance, and can be accessed by derived classes according to visibility (public, protected, private).

The difference between static and non static members is only that a non static member is tied to an instance of a class although a static member is tied to the class, and not to a particular instance.
That is, a static member is shared by all instances of a class although a non static member exists for each instance of class.

class Derived extends Base
<
public function __construct()
<
$this->a = 0;
parent::$b = 0;
>
public function f()
<
$this->a++;
parent::$b++;
>
>

$i1 = new Derived;
$i2 = new Derived;

To check if a method declared in a class is static or not, you can us following code. PHP5 has a Reflection Class, which is very helpful.

It is important to understand the behavior of static properties in the context of class inheritance:

— Static properties defined in both parent and child classes will hold DISTINCT values for each class. Proper use of self:: vs. static:: are crucial inside of child methods to reference the intended static property.

— Static properties defined ONLY in the parent class will share a COMMON value.

declare( strict_types = 1 );

$a = new staticparent ;
$a = new staticchild ;

It should be noted that in ‘Example #2’, you can also call a variably defined static method as follows:

Static variables are shared between sub classes

class Child1 extends MyParent <

class Child2 extends MyParent <

To check if a function was called statically or not, you’ll need to do:

(I’ll add this to the manual soon).

The static keyword can still be used (in a non-oop way) inside a function. So if you need a value stored with your class, but it is very function specific, you can use this:

echo aclass::b(); //24
echo aclass::b(); //36
echo aclass::b(); //48
echo aclass::$d; //fatal error

Starting with php 5.3 you can get use of new features of static keyword. Here’s an example of abstract singleton class:

abstract class Singleton <

/**
* Prevent direct object creation
*/
final private function __construct ()

/**
* Prevent object cloning
*/
final private function __clone ()

On PHP 5.2.x or previous you might run into problems initializing static variables in subclasses due to the lack of late static binding:

If the init() method looks the same for (almost) all subclasses there should be no need to implement init() in every subclass and by that producing redundant code.

Solution 1:
Turn everything into non-static. BUT: This would produce redundant data on every object of the class.

Short example on a DataRecord class without error checking:

Regarding the initialization of complex static variables in a class, you can emulate a static constructor by creating a static function named something like init() and calling it immediately after the class definition.

/*
this is the example to use new class with static method..
i hope it help
*/

It’s come to my attention that you cannot use a static member in an HEREDOC string. The following code

function __construct()
<
echo

Inheritance with the static elements is a nightmare in php. Consider the following code:

class DerivedClassOne extends BaseClass <
>

class DerivedClassTwo extends BaseClass <
>

At this point I think it is a big pity inheritance does not work in case of static variables/methods. Keep this in mind and save your time when debugging.

Hi, here’s my simple Singleton example, i think it can be useful for someone. You can use this pattern to connect to the database for example.

$objA = MySingleton :: getInstance (); // Object created!

$objB = MySingleton :: getInstance ();

Источник

How can I call a static method on a variable class?

I’m trying to make some kind of function that loads and instantiates a class from a given variable. Something like this:

If I use it like this:

It should include and instantiate the session class.

BTW: the static getInstance function comes from this code:

The thing is that right now the way to use the functions in a class is this:

6 Answers 6

Calling static functions on a variable class name is apparently available in PHP 5.3:

Could definitely use that right now myself.

Until then you can’t really assume that every class you are loading is designed to be a singleton. So long as you are using

The first argument is a callback type containing the classname and method name in this case.

Why not use __autoload() function?

then you just instantiate object when needed.

It looks like you are fighting PHP’s current implementation static binding, which is why you are jumping through hoops with getCallingClass. I can tell you from experience, you should probably abandon trying to put instantiation in a parent class through a static method. It will cause you more problems in the end. PHP 5.3 will implement «late static binding» and should solve your problem, but that obviously doesn’t help now.

You are probably better off using the autoload functionality mentioned by kodisha combined with a solid Singleton implementation. I’m not sure if your goal is syntactic sugar or not, but it think you will do better in the long run to steer clear of trying to save a few characters.

Off the top of my head, needs testing, validation etc:

Late static bindings will work for you I think. In the construct of each class do:

Then. Here is an autoloader I created. See if this solves your dilemma.

Then all you have to do is

but you have to have a php file in the path with the name ClassName.php where ClassName is the same as the name of the class you want to instantiate.

php static class in class. Смотреть фото php static class in class. Смотреть картинку php static class in class. Картинка про php static class in class. Фото php static class in class

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *