php определить класс переменной

Основы

class

Каждое определение класса начинается с ключевого слова class, затем следует имя класса, и далее пара фигурных скобок, которые заключают в себе определение свойств и методов этого класса.

Именем класса может быть любое слово, при условии, что оно не входит в список зарезервированных слов PHP, начинается с буквы или символа подчеркивания и за которым следует любое количество букв, цифр или символов подчеркивания. Если задать эти правила в виде регулярного выражения, то получится следующее выражение: ^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$.

Класс может содержать собственные константы, переменные (называемые свойствами) и функции (называемые методами).

Пример #1 Простое определение класса

class B
<
function bar ()
<
// Замечание: следующая строка вызовет предупреждение, если включен параметр E_STRICT.
A :: foo ();
>
>

// Замечание: следующая строка вызовет предупреждение, если включен параметр E_STRICT.
B :: bar ();
?>

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

Для создания экземпляра класса используется директива new. Новый объект всегда будет создан, за исключением случаев, когда он содержит конструктор, в котором определен вызов исключения в случае ошибки. Рекомендуется определять классы до создания их экземпляров (в некоторых случаях это обязательно).

Если с директивой new используется строка ( string ), содержащая имя класса, то будет создан новый экземпляр этого класса. Если имя находится в пространстве имен, то оно должно быть задано полностью.

Пример #3 Создание экземпляра класса

В контексте класса можно создать новый объект через new self и new parent.

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

Пример #4 Присваивание объекта

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

В PHP 5.3.0 введены несколько новых методов создания экземпляров объекта:

Пример #5 Создание новых объектов

class Test
<
static public function getNew ()
<
return new static;
>
>

class Child extends Test
<>

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

extends

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

Наследуемые методы и свойства могут быть переопределены (за исключением случаев, когда метод класса объявлен как final) путем объявления их с теми же именами, как и в родительском классе. Существует возможность доступа к переопределенным методам или статическим методам путем обращения к ним через parent::

Пример #6 Простое наследование классов

class ExtendClass extends SimpleClass
<
// Переопределение метода родителя
function displayVar ()
<
echo «Расширенный класс\n» ;
parent :: displayVar ();
>
>

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

::class

Начиная с версии PHP 5.5 можно использовать ключевое слово class для разрешения имени класса. С помощью конструкции ClassName::class можно получить строку с абсолютным именем класса ClassName. Обычно это довольно полезно при работе с классами, использующими пространства имен.

Пример #7 Разрешение имени класса

namespace NS <
class ClassName <
>

Источник

Функции работы с классами и объектами

Содержание

User Contributed Notes 19 notes

[Editor’s note: If you are trying to do overriding, then you can just interrogate (perhaps in the method itself) about what class (get_class()) the object belongs to, or if it is a subclass of a particular root class.

You can alway refer to the parent overriden method, see the «Classes and Objects» page of the manual and comments/editor’s notes therein.]

There is no function to determine if a member belongs to a base class or current class eg:

class foo <
function foo () < >
function a () < >
>

class bar extends foo <
function bar () < >
function a () < >
>

lala = new Bar ();
?>
——————
how do we find programmatically if member a now belongs to class Bar or Foo.

To pillepop2003 at yahoo dot de:

I have the same issue. I have a base class that manages database tasks for a number of child classes. One of the functions in the base class is a find() method that returns instances of the child classes. Since find() is usually called as a static method, it needs to know the name of the child class. As you’ve found, this appears to be impossible to get in an easy fashion.

The only way I’ve found to get the child class name is to use the debug_traceback() function. This requires me to have a find() method in every child class, but it does work.

function find () <
return parent :: find ();
>
>

function find () <
return parent :: find ();
>
>

FYI: if you want to split your class into manageble chunks, what means different files for you, you can put you functoins into includes, and make include() have a return value. Like this:

And your included file:

Then your function call will be:

$instance = new Some_class ();
$instance->add_value (3);

And this will return
6
hopefully 😛

Keep in mind though, that the scope in the included file will be identical to the scope the function ‘add_value’ has.
And if you want to return the outcome, you should also have a return statement made in your include as well.

Something I found out just now that comes in very handy for my current project:

it is possible to have a class override itself in any method ( including the constructor ) like this:

in this case assuming that class b is already defined and also has the method ha ( )

note that the code after the statement to override itself is still executed but now applies to the new class

i did not find any information about this behaviour anywhere, so i have no clue wether this is supposed to be like this and if it might change. but it opens a few possibilities in flexible scripting!!

Re: Looking for an uninstantiated class

Why would I do this? Because I have my class layouts the same as their respective tables; the factory then selects the data (making sure that the variables match) and plugs in the data. (I’ve left out the actual code to do the selection/insertion).

To pillepop2003 at yahoo dot de:

It seems to me if there really is no nice way to get the class name in an un-instanciated class, there is a workaround in PHP5 though using static/class variables.

?>

However, you’ll need to have at least instanciated an object of the class myFooExtended before calling getClassName or introduce some other initialization (the class variable will need to be set at some point to __CLASS__ in the sub-class).

If you want to be able to call an instance of a class from within another class, all you need to do is store a reference to the external class as a property of the local class (can use the constructor to pass this to the class), then call the external method like this:

or if the double ‘->’ is too freaky for you, how about:

This is handy if you write something like a general SQL class that you want member functions in other classes to be able to use, but want to keep namespaces separate. Hope that helps someone.

I wanted to dynamically choose an extender for a class. This took awhile of playing with it but I came up with a solution. Note that I can’t verify how safe it is, but it appears to work for me. Perhaps someone else can shed light on the details:

Practical application: I have a database abstraction system that has individual classes for mysql, pgsql, et al. I want to be able to create a global db class that extends one of the individual db classes depending on the application configuration.

I know that there are probably much better ways of doing this but I haven’t reached that level when it comes to classes.

to covertka at muohio dot edu and pillepop2003 at yahoo dot de:

There’s a much easier solution to getting a class’ name for working with a factory function. Let’s assume you’re doing something like this:

?>

Now, consider the named parameter idiom and remember that PHP uses hashes for everything; as a result make the following changes:

?>

Nice ‘n simple. It seems that what the original poster wanted was something like C++ static data members; unfortunately as PHP4 has no static variables at all, there would need to be significant language change to support static-like behavior. If you move to PHP5, the static keyword solves your problem cleanly.

To access an object member with an illegal character in the name, use this syntax:

This is particularly relevant with the dynamically-generated classes used by, for instance, database objects and the SoapClient class.

Subject: using «sql_calc_found_rows» in a MySQL query while exploiting result in a PHP db class object.

There is a nice function in MySQL that allows to know how many records would have been returned if no «where» clause were set : SQL_CALC_FOUND_ROWS.

If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.

Then, the only way to get the right result seems to be the use of a class function, like :

A small function that allows finding all references to the object. Written in 3 minutes and may be buggy (for ex pass object as reference in some places?)

Why do u want to know the classname of an non-existant object?

The only possible explanation for this question seems to me u want to know the class before u instantiate the object. Well, this is of no use since u always instantiate a class of ur choice.

When the class is instantiated into an object u can find the class of the object by means of get_class(). This is all u need. In case of inheritance u can use get_class($this) to get the class of the instantiated object. Now u can differentiate according to which class the object belongs to.

$object1 = new A ();
$object2 = new B ();
?>

When u run this code-snippet the output will be:

Object is an instance of class A which is the parent-class.
Object is an instance of class B which is the child-class.

We have an array with many objects in a style like

Because there is no function in php api, we made the following function.

Warning: function is very slow and should only be called if it’s necessary for debugging reasons:

// clean the output-buffer
ob_end_clean ();

// cache the last match
$lastMatch = array();

// the return value
$return = array();

?>

I know, it’s not that elegant but I hope it’s useful for a few people.

Источник

Классы и объекты в PHP

Класс — это шаблон для объектов, а объект — это экземпляр класса.

Что такое класс PHP?

Синтаксис

Ключевое слово class используется для определения класса в PHP. Ниже приведены правила создания класса в PHP:

Как добавить свойства к классу?

Мы вызываем свойства внутри класса. Свойства могут принимать такие значения, как строки, целые числа и логические значения (true/false), как и любые другие переменные. Добавим несколько свойств в класс Car:

Приведем правила создания свойств к классу:

Пример

Данный код ничего не выведет, поскольку мы создали класс, но не создали пока ни одного объекта.

Примечание: В классе переменные называются свойствами, а функции — методами!

Что такое объект PHP?

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

Процесс создания объекта также известен как создание экземпляра.

Объекты, для чего они нужны?

В то время как в процедурном стиле программирования все функции и переменные находятся вместе в глобальной области видимости таким образом, чтобы их можно было использовать, просто вызывая их имя, использование классов делает манипуляции с кодом внутри классов скрытыми от глобальной области. Это происходит потому, что код внутри классов инкапсулируется в пределах класса, вне досягаемости глобальной области. Итак, нам нужен способ, позволяющий коду из глобальной области видимости использовать код внутри класса, и этот способ базируется на создании объектов из класса.

Мы можем создать столько объектов, сколько захотим, из одного и того же класса, и все они будут совместно использовать методы и свойства класса. См. изображение ниже:

Хотя все объекты были созданы из одного и того же класса и, следовательно, имеют методы и свойства класса, они все же разные. Это не только потому, что они имеют разные названия, но и потому, что их свойствам могут быть присвоены разные значения. Например, на изображении выше они различаются свойством цвета: Mercedes зеленый, Bmw синий, а Audi оранжевый.

Примечание: Класс содержит методы и свойства, общие для всех созданных из него объектов.

Хотя объекты используют один и тот же код, они могут вести себя по-разному, поскольку им могут быть присвоены разные значения.

Как получить свойства объекта?

Создав объект, мы можем получить его свойства. Например:

Пример

Результат выполнения кода:

Свойство color было установлено в классе по умолчанию (green), поэтому все объекты его унаследовали.

Как установить свойства объекту?

Чтобы установить свойство объектe, мы используем аналогичный подход.

Например, установим синий цвет объекту bmw :

Пример

Результат выполнения кода:

Как добавить методы в класс?

Классы могут содержать различные функции. Функция внутри класса называется методом. Здесь мы добавляем в класс метод hello() с префиксом public :

Правила создания методов:

Мы можем подходить к методам так же, как и к свойствам:

Пример

Пример

Результат выполнения кода:

Пример

Результат выполнения кода:

Пример

Сделать это можно двумя способами:

Пример

Результат выполнения кода:

Пример

Результат выполнения кода:

Является ли объект экземпляром класса?

Оператор instanceof используется для определения того, является ли текущий объект экземпляром указанного класса:

Пример

Результат выполнения кода:

Итоги

Источник

get_class

(PHP 4, PHP 5, PHP 7, PHP 8)

get_class — Возвращает имя класса, к которому принадлежит объект

Описание

Список параметров

Тестируемый объект. Внутри класса этот параметр может быть опущен.

Возвращаемые значения

Если параметр object опущен внутри класса, будет возвращено имя этого класса.

Если параметр object является экземпляром класса, существующего в пространстве имён, то будет возвращено полное имя с указанием пространства имён.

Ошибки

Список изменений

ВерсияОписание
7.2.0До этой версии значением по умолчанию для object было null с тем же эффектом, что и отсутствие передачи значения. Теперь null был удалён как значение по умолчанию для object и больше не является допустимым значением.

Примеры

Пример #1 Использование get_class()

// создание объекта
$bar = new foo ();

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

Пример #2 Использование get_class() в родительском классе

class foo extends bar <
>

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

Пример #3 Использование get_class() с классами в пространствах имён

namespace Foo \ Bar ;

class Baz <
public function __construct ()
<

$baz = new \ Foo \ Bar \ Baz ;

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

Смотрите также

User Contributed Notes 36 notes

::class
fully qualified class name, instead of get_class

namespace my \ library \ mvc ;

print Dispatcher ::class; // FQN == my\library\mvc\Dispatcher

$disp = new Dispatcher ;

(For reference, here’s the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)

If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

class Foo
<
public function __construct ()
<
echo «Foo» ;
>
>

People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here’s a good example that should fix that for ever:

class Bar extends Foo <

$foo = new Foo ();
$bar = new Bar ();
$quux = new Quux ();

—doMethod—
Foo::doMethod
Foo::doMethod
Quux::doMethod

—doGetClassThis—
Foo::doThat
Bar::doThat
Quux::doThat

—doGetClass—
Foo::doThat
Foo::doThat
Quux::doThat

In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not ‘know’ the name of the calling subclass’, so I use a backtrace to determine it. I don’t like hacks like this, but as long as PHP doesn’t have an alternative, this is what has to be done:

Simplest way how to gets Class without namespace

namespace a \ b \ c \ d \ e \ f ;

echo new Foo (); // prints Foo
?>

Need a quick way to parse the name of a class when it’s namespaced? Try this:

/**
* Obtains an object class name without namespaces
*/
function get_real_class($obj) <
$classname = get_class($obj);

With regard to getting the class name from a namespaced class name, then using basename() seems to do the trick quite nicely.

namespace Foo \ Bar ;

class Snafu extends Baz
<
>

__CLASS__ Foo\Bar\Baz Baz
get_called_class Foo\Bar\Snafu Snafu

The code in my previous comment was not completely correct. I think this one is.

/**
* Returns the classname of the child class extending this class
*
* @return string The class name
*/
private static function getClass() <
$implementing_class = static::$__CLASS__;
$original_class = __CLASS__;

There are discussions below regarding how to create a singleton that allows subclassing. It seems with get_called_class there is now a cleaner solution than what is discussed below, that does not require overriding a method per subclass.

private function __construct () <
// Singleton
>
>

class MySubclass extends MySuperclass <
>

Although you can call a class’s static methods from an instance of the class as though they were object instance methods, it’s nice to know that, since classes are represented in PHP code by their names as strings, the same thing goes for the return value of get_class():

If you want the path to an file if you have i file structure like this

and foo() in foo.php extends controller() in controller.php like this

namespace system \ modules \ foo ;

class foo extends \ system \ libs \ controller <
public function __construct () <
parent :: __construct ();
>
>
?>

and you want to know the path to foo.php in controller() this may help you

namespace system \ libs ;

well, if you call get_class() on an aliased class, you will get the original class name

Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it’s not available. Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

default: throw new Exception ( «Unknown backtrace method type» );
>
>
>

class B extends Singleton <
>

class C extends Singleton <
>

Method for pulling the name of a class with namespaces pre-stripped.

namespace testme \ here ;

public function test ()
<
return get_class_name ( get_class ());
>
>

As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the «self» keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the «self» keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

public static function classDisplayName ()
<
return ‘Base Class’ ;
>

public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>

However, assuming compile-time binding (where the keyword «self» refers to the class in which the method is defined), which is how php works, the output would be:

The oddity here is that «$this» is bound at runtime to the actual class of the object (obviously) but «self» is bound at compile-time, which seems counter-intuitive to me. «self» is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which «self» ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to «self» being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the «self» keyword for static methods:

public static function classDisplayName ()
<
return ‘Base Class’ ;
>

public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>

I realise that some people might respond «why don’t use just just the class name with ‘ Class’ appended instead of the classDisplayName() method», which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.

Источник

Впервые базовая поддержка классов в PHP была введена в 4 версии языка, но затем для более полной поддержки ООП повторно реализована для 5 версии. Сегодня PHP пригоден для работы с классами, но в то же время библиотека языка до сих пор в основном состоит из функций, классы теперь добавляются в различных целях. Тем не менее, основным средством PHP является использование своих собственных классов.

Классы можно рассматривать как совокупность методов, переменных и констант. Они часто отражают реальные предметы, как класс автомобиля или класс фруктов. Вы объявляете класс только один раз, но можете создать множество его экземпляров, которые могут храниться в памяти. Экземпляр класса обычно называют объектом. Если вы все еще немного путаетесь в том, какие классы и зачем они нужны, не волнуйтесь. В этой статье мы напишем наш самый первый класс и используем его.

Классы в PHP — определение и использование

После введения в классы в PHP мы готовы написать наш собственный класс. Он будет содержать информацию об основном пользователе, например, вашего сайта.

На данный момент этот класс PHP ничего не может сделать. Мы можем создать экземпляр, это делается с помощью ключевого слова new :

Попробуем использовать наш новый класс php. Следующий код должен идти после того, как класс был объявлен или подключен:

Результат должен выглядеть следующим образом:

Конструкторы и деструкторы

Конструктор и деструктор — специальные функции, которые автоматически вызываются, когда объект создается и уничтожается. Из них наиболее полезным является конструктор, потому что позволяет при создании нового объекта передавать ему параметры, которые затем используются для инициализации переменных объекта. Вот пример класса с простым конструктором:

Конструктор выглядит как обычная функция, за исключением того, что начинается с двух символов нижнего подчеркивания. В PHP так указывается волшебная функция, которая обладает дополнительной функциональностью по сравнению с обычными функциями. Таким образом, функция типа « __construct «, является конструктором класса и будет вызываться автоматически при создании объекта. Давайте попробуем сделать это в следующем PHP class примере:

С помощью этой строки кода будет создан объект, вызван конструктор и в нем выполнится код, что приведет к выводу строки “ I’m alive! ”. Но как уже упоминалось ранее, основным преимуществом конструктора является возможность передавать параметры, которые могут быть использованы для инициализации переменных – членов класса.

Давайте попробуем сделать это:

Объявление конструктора с параметрами такое же, как объявление функции, и передача параметров очень похожа на вызов обычной функции, но с ключевым словом “ new ”. Конструктор может иметь столько параметров, сколько вам хочется.

Деструкторы

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

Как видите, деструктор такой же как конструктор, только имя отличается. Если попробуете запустить этот пример, то сначала увидите сообщение конструктора, а затем название животного, которое мы вручную выводим в последней строке. После этого сценарий заканчивается, объект уничтожается деструктором, и выводится сообщение о нашем бедном умершем животном.

Источник

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

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