I have a base class Product , I need to add a function, that is, to expand its capabilities without touching the class itself and its parent classes.

  • congratulations! what have inheritance then? - teran pm
  • It is not possible to do this in php - L. Vadim
  • мне нужно добавить функцию, тоесть расширить его возможности не трогая сам класс - is it even like? I, something did not understand the question, how can I add something without touching the class or object? - And

1 answer 1

As I understand it, you want to see in PHP extension functions. Unfortunately, they are not in PHP.

1) The most true path is to create a descendant class of MyProduct extends Product and add a method there

2) Masochistic variant - you can use the runkit extension, specifically, the runkit_method_add method and add a method in runtime

3) The third way is to create a function (and preferably a utility class with a static method) with a receiver. Those. the one to which your object will be passed as the first parameter and implement the logic in it. If inside this function private fields are needed, then you can use reflection, although this is ah-ah-ah.