php call function from class

I’m learning OOP PHP. I want to call a method from another class to a new class.

For just a example:

And i want to call the method aMethod from the class ‘Aclass‘ into the new class.

php call function from class. Смотреть фото php call function from class. Смотреть картинку php call function from class. Картинка про php call function from class. Фото php call function from class

2 Answers 2

Example

Example

Also your function aMethod in Aclass should have public or protected visibility. Public if you create an instance, protected if you extends. More informations can be found in manuals at the end.

Example

You can of course use both methods not only in __construct but also in other functions.

Manuals

For this I’d use dependency injection. Which is just a fancy way of saying «sending an object of the A class when creating B «.

In other words, something like this:

Constructors are meant to be used to create an object that’s ready to be used, which is why I’ve just stored the dependency inside the typeB object itself. Then, in the getTest() method I invoke the test() method of the object I’m depending upon, in order to get the needed data from it.
Doing it in this manner will allow you to write flexible OOP code, which can easily be expanded and extended as you require. Hiding the dependencies inside the constructors, by creating objects there, creates a hidden and hard dependency. Something which makes it a lot harder, if not down right impossible, to properly leverage the extensible nature of the class-based designs.

Источник

Особенности при перехватах вызовов методов с помощью __call() и __callStatic() в PHP

Пролог

Что такое __call() и __callStatic()?

Начнём с простого: у вас есть класс, описывающий методы и свойства какого-либо объекта (что, в принципе, логично). Представьте, что вы решили обратиться к несуществующему методу этого объекта. Что вы получите? Правильно — фатальную ошибку! Ниже привожу простейший код.

В статическом контексте наблюдаем аналогичное поведение:

Так вот, иногда возникает необходимость либо выполнить какой-то код при отсутствии нужного нам метода, либо узнать какой метод пытались вызвать, либо использовать другое API для вызова нужного нам метода. С этой целью и существуют методы __call() и __callStatic() — они перехватывают обращение к несуществующему методу в контексте объекта и в статическом контексте, соответственно.
Перепишем наши примеры с использованием «магических методов». Примечание: Каждый из этих волшебников принимает два параметра: первый — имя метода, который мы пытаемся вызвать, второй — список, содержащий параметры вызываемого метода. Ключ — номер параметра вызываемого метода, значение — собственно сам параметр:

Практическое применение этих двух товарищей зависит только от вашей фантазии. В качестве примера, приведу набросок реализации техники программирования Fluent Interface (некоторые считают это паттерном проектирования, но от названия суть не меняется). Коротко говоря, fluent interface позволяет составлять цепочки вызовов объектов (с виду что-то похожее на jQuery). На хабре есть пару статей про реализацию такого рода алгоритмов. На ломаном русском переводе fluent interfaces звучат как «текучие интерфейсы»:

Ты кажется хотел рассказать нам что-то про особенности перехвата?

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

Обновил страничку. Моему удивлению не было предела. Я сразу побежал на php.net смотреть мануал.
Вот выдержка из документации

В контексте объекта при вызове недоступных методов вызывается метод __call().
В статическом контексте при вызове недоступных методов вызывается метод __callStatic().

Я долго не мог понять в чём проблема. Версия PHP: 5.4.13. То есть те времена, когда вызовы несуществующих методов из любого контекста приводили к вызову __call() давно прошли. Почему вместо логичной Fatal Error, я получаю вызов __call()? Я пошёл исследовать дальше. Добавил в абстрактный класс Base метод __callStatic(). Снова обновил страницу. Вызов по-прежнему адресовался в __call(). Промучавшись полдня, всё-таки понял в чём была проблема. Оказывается PHP воспринимает статический контекст внутри класса и вне его по-разному. Не поняли? Попытаюсь проиллюстрировать. Возьмём предыдущий пример и добавим в него одну строчку:

То есть статический контекст — статическому контексту рознь.
Чудеса да и только. Когда я изучал «магические методы», я не думал, что название стоит воспринимать настолько буквально.

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

Резюме

Если для вас ещё не всё понятно: речь идёт о том, что обращение к статическому методу внутри экземпляра класса и обращение к статическому методу вне экземпляра класса — воспринимаются интерпретатором по-разному. Если вы поменяете self::Launch() на Main::Launch() контекст вызова не изменится. Поведение в этом случае будет одинаковым. Опять же, проиллюстрирую:

Итог статьи прост: будьте внимательными (впрочем, как и всегда) и проверяйте поведение при вызовах методов.

Источник

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 call function from class. Смотреть фото php call function from class. Смотреть картинку php call function from class. Картинка про php call function from class. Фото php call function from 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.

Источник

Calling a function within a Class method?

I have been trying to figure out how to go about doing this but I am not quite sure how.

Here is an example of what I am trying to do:

Here is the part I am having problems with, how do I call bigTest()?

10 Answers 10

The sample you provided is not valid PHP and has a few issues:

The syntax should rather be:

Second, wrapping the bigTest() and smallTest() functions in public function() <> does not make them private — you should use the private keyword on both of these individually:

Also, it is convention to capitalize class names in class declarations (‘Test’).

php call function from class. Смотреть фото php call function from class. Смотреть картинку php call function from class. Картинка про php call function from class. Фото php call function from class

I think you are searching for something like this one.

php call function from class. Смотреть фото php call function from class. Смотреть картинку php call function from class. Картинка про php call function from class. Фото php call function from class

php call function from class. Смотреть фото php call function from class. Смотреть картинку php call function from class. Картинка про php call function from class. Фото php call function from class

php call function from class. Смотреть фото php call function from class. Смотреть картинку php call function from class. Картинка про php call function from class. Фото php call function from class

In order to have a «function within a function», if I understand what you’re asking, you need PHP 5.3, where you can take advantage of the new Closure feature.

You need to call newTest to make the functions declared inside that method “visible” (see Functions within functions). But that are then just normal functions and no methods.

Источник

Please see the code bellow:

Now, the problem is the constructor is called in line 09

But i want to call it manually at line 11-13

Is it possible? If then how? Any idea please?

php call function from class. Смотреть фото php call function from class. Смотреть картинку php call function from class. Картинка про php call function from class. Фото php call function from class

6 Answers 6

Why not just do this?

EDIT: I just thought of a hacky way you could prevent a constructor from being called (sort of). You could subclass Test and override the constructor with an empty, do-nothing constructor.

This is might make sense if you’re dealing with some code that you cannot change for some reason and need to work around some annoying behavior of a poorly written constructor.

Note that if the constructor (__construct method) contains arguments passed by reference, then the function:

will fail with an error.

I suggest you to use Reflection class instead; here is how you can do so:

php call function from class. Смотреть фото php call function from class. Смотреть картинку php call function from class. Картинка про php call function from class. Фото php call function from class

I don’t know if there are some security concerns by using the eval() method, but you could make yourself a function like this:

If separating instantiation from initialization isn’t strictly a requirement, there are two other possibilities: first, a static factory method.

Or, if you’re using php 5.3.0 or higher, you can use a lambda:

The initialization method described by Asaph is great if for some reason you have a need to logically separate initialization from instantiation, but if supporting your use case above is a special case, not a regular requirement, it can be inconvenient to require users to instantiate and initialize your object in two separate steps.

The factory method is nice because it gives you a method to call to get an initialized instance. The object is initialized and instantiated in the same operation, though, so if you have a need to separate the two it won’t work.

And lastly, I recommend the lambda if this initialization mechanism is uncommonly used, and you don’t want to clutter your class definition with initialization or factory methods that will hardly ever be used.

Источник

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

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