php class call class function

I’m developing a club membership register web application and I am a fairly newbie when it comes to oop. The problem I’m having is that I would need to call a function outside a class, but I know you can’t do that in PHP and I need to solve it somehow.

This code will demonstrate what my problem is:

I’ve written the code for database actions in a separate file called database_functions.php, but I can’t include that file inside a class. What I need to know is how can I access those functions without having to write them again inside the class? (I have written applications before with VB.Net and in it I can use functions of the current project inside classes.)

5 Answers 5

you can use require_once() with exact path of that class after that you should use the object of the included class and function name for calling the function of outer class.

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

If you have a main file that calls different files (via include or require ), then you can use any function that will exist in global namespace just fine in that class, provided the function you call will always exist in global namespace.

The other options is to wrap the other functions you have inside another class, provided that it makes sense. Class A could then hold a field with a class B object and call B ‘s functions as it pleases.

The benefit of this is that everything is abstracted in classes. Once you’re outside of the class, all you have to know is what methods (functions) you can use of a class and you won’t have to worry about the implementation details. A direct advantage of this is that you don’t have to pass the same parameter to same functions all the time, say, if you need a database handler to execute SQL code within a function. A class could just hold such an instance and you won’t have to repeat the same parameter all the time.

An additional advantage is that your global namespace won’t be polluted with specific functions.

Источник

Особенности при перехватах вызовов методов с помощью __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() контекст вызова не изменится. Поведение в этом случае будет одинаковым. Опять же, проиллюстрирую:

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

Источник

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

I think you are searching for something like this one.

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

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

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

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.

Источник

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

Содержание

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 class call class function

A class may contain its own constants, variables (called «properties»), and functions (called «methods»).

Example #1 Simple Class definition

Output of the above example in PHP 7:

Output of the above example in PHP 8:

To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

If there are no arguments to be passed to the class’s constructor, parentheses after the class name may be omitted.

Example #3 Creating an instance

When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example #4 Object Assignment

The above example will output:

It’s possible to create instances of an object in a couple of ways:

Example #5 Creating new objects

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

class Child extends Test
<>

The above example will output:

It is possible to access a member of a newly created object in a single expression:

Example #6 Access member of newly created object

The above example will output something similar to:

Note: Prior to PHP 7.1, the arguments are not evaluated if there is no constructor function defined.

Properties and methods

Class properties and methods live in separate «namespaces», so it is possible to have a property and a method with the same name. Referring to both a property and a method has the same notation, and whether a property will be accessed or a method will be called, solely depends on the context, i.e. whether the usage is a variable access or a function call.

Example #7 Property access vs. method call

public function bar () <
return ‘method’ ;
>
>

The above example will output:

That means that calling an anonymous function which has been assigned to a property is not directly possible. Instead the property has to be assigned to a variable first, for instance. It is possible to call such a property directly by enclosing it in parentheses.

Example #8 Calling an anonymous function stored in a property

The above example will output:

extends

A class can inherit the constants, methods, and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.

The inherited constants, methods, and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method as final, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.

Example #9 Simple Class Inheritance

class ExtendClass extends SimpleClass
<
// Redefine the parent method
function displayVar ()
<
echo «Extending class\n» ;
parent :: displayVar ();
>
>

The above example will output:

Signature compatibility rules

When overriding a method, its signature must be compatible with the parent method. Otherwise, a fatal error is emitted, or, prior to PHP 8.0.0, an E_WARNING level error is generated. A signature is compatible if it respects the variance rules, makes a mandatory parameter optional, and if any new parameters are optional. This is known as the Liskov Substitution Principle, or LSP for short. The constructor, and private methods are exempt from these signature compatibility rules, and thus won’t emit a fatal error in case of a signature mismatch.

Example #10 Compatible child methods

The above example will output:

The following examples demonstrate that a child method which removes a parameter, or makes an optional parameter mandatory, is not compatible with the parent method.

Example #11 Fatal error when a child method removes a parameter

class Extend extends Base
<
function foo ()
<
parent :: foo ( 1 );
>
>

Output of the above example in PHP 8 is similar to:

Example #12 Fatal error when a child method makes an optional parameter mandatory

Output of the above example in PHP 8 is similar to:

Renaming a method’s parameter in a child class is not a signature incompatibility. However, this is discouraged as it will result in a runtime Error if named arguments are used.

Example #13 Error when using named arguments and parameters were renamed in a child class

The above example will output something similar to:

::class

Example #14 Class name resolution

namespace NS <
class ClassName <
>

The above example will output:

The class name resolution using ::class is a compile time transformation. That means at the time the class name string is created no autoloading has happened yet. As a consequence, class names are expanded even if the class does not exist. No error is issued in that case.

Example #15 Missing class name resolution

The above example will output:

As of PHP 8.0.0, the ::class constant may also be used on objects. This resolution happens at runtime, not compile time. Its effect is the same as calling get_class() on the object.

Example #16 Object name resolution

The above example will output:

Nullsafe methods and properties

The effect is similar to wrapping each access in an is_null() check first, but more compact.

Example #17 Nullsafe Operator

The nullsafe operator is best used when null is considered a valid and expected possible value for a property or method return. For indicating an error, a thrown exception is preferable.

User Contributed Notes 11 notes

I was confused at first about object assignment, because it’s not quite the same as normal assignment or assignment by reference. But I think I’ve figured out what’s going on.

First, think of variables in PHP as data slots. Each one is a name that points to a data slot that can hold a value that is one of the basic data types: a number, a string, a boolean, etc. When you create a reference, you are making a second name that points at the same data slot. When you assign one variable to another, you are copying the contents of one data slot to another data slot.

Now, the trick is that object instances are not like the basic data types. They cannot be held in the data slots directly. Instead, an object’s «handle» goes in the data slot. This is an identifier that points at one particular instance of an obect. So, the object handle, although not directly visible to the programmer, is one of the basic datatypes.

What makes this tricky is that when you take a variable which holds an object handle, and you assign it to another variable, that other variable gets a copy of the same object handle. This means that both variables can change the state of the same object instance. But they are not references, so if one of the variables is assigned a new value, it does not affect the other variable.

Источник

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

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