Php add methods to class

PHP — Add a method to a class

If the class in question implements __call magic, then it’s possible, and quite easy. If you want to know how this works I suggest you read Extending objects with new methods at runtime., How to keep pee from splattering from the toilet all around the basin and on the floor on old toilets that are really low and have deep water? , Hmm. This doesn’t actually add a method to the original object like swift extensions (entirely different from any type of inheritance or php extends), but it is a design workaround that essentially does the trick. – ScottyBlades Oct 6 ’19 at 4:10 , 1 @johannes It’s sometimes useful when debugging. But that’s the reason for my recommendation, which does not, however, prevent me from actually answering the question. – Artefacto Jun 10 ’10 at 6:01

If you only need to access the Public API of the class, you can use a Decorator:

class SomeClassDecorator < protected $_instance; public function myMethod() < return strtoupper( $this->_instance->someMethod() ); > public function __construct(SomeClass $instance) < $this->_instance = $instance; > public function __call($method, $args) < return call_user_func_array(array($this->_instance, $method), $args); > public function __get($key) < return $this->_instance->$key; > public function __set($key, $val) < return $this->_instance->$key = $val; > // can implement additional (magic) methods here . > 

Then wrap the instance of SomeClass:

$decorator = new SomeClassDecorator(new SomeClass); $decorator->foo = 'bar'; // sets $foo in SomeClass instance echo $decorator->foo; // returns 'bar' echo $decorator->someMethod(); // forwards call to SomeClass instance echo $decorator->myMethod(); // calls my custom methods in Decorator 

Answer by Queen Brown

is_a — Checks if the object is of this class or has this class as one of its parents,get_class — Returns the name of the class of an object,get_declared_classes — Returns an array with the name of the defined classes,is_subclass_of — Checks if the object has this class as one of its parents or implements it

 [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: 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. 

Answer by Averi Ashley

If you only need to access the Public API of the class, you can use a Decorator:,If you need to have access to the protected API, you have to use inheritance. If you need to access the private API, you have to modify the class files. While the inheritance approach is fine, modifiying the class files might get you into trouble when updating (you will lose any patches made). But both is more feasible than using runkit.,I’d prefer the inheritance way. It’s a lot easier to handle in the long run.,You can use the runkit extension for this, but you should really consider regular inheritance instead.

Читайте также:  Html text transform italic

I’m using WordPress as a CMS, and I want to extend one of its classes without having to inherit from another class; i.e. I simply want to «add» more methods to that class:

function insert_this_function_into_class_A()
A::insert_this_function_into_class_A(); # b 

Answer by Ian Fox

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.,Note: In a class, variables are called properties and functions are called methods!,A class is a template for objects, and an object is an instance of class.,2. Outside the class (by directly changing the property value):

Define a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces (<>). All its properties and methods go inside the braces:

Answer by Aspyn Sims

The classes most often contain functions. A function inside a class is called a method. Here we add the method hello() to the class with the prefix public.,With this tutorial, we are going to take our first steps into the world of object oriented programming by learning the most basic terms in the field:,If so, the eBook»The essentials of object oriented PHP» can further help you.,Home >> Object Oriented PHP tutorials >> Classes, objects, methods and properties

Answer by Alonzo Rivera

The get_class_methods() function is an inbuilt function in PHP which is used to get the class method names.,Below programs illustrate the get_class_methods() function in PHP:,Parameters: This function accepts a single parameter $class_name which holds the class name or an object instance.,PHP | get_class_methods() Function

array get_class_methods( mixed $class_name )

Источник

PHP Objects

Summary: in this tutorial, you will learn about PHP objects, how to define a class, and how to create an object from a class.

What is an Object

If you look at the world around you, you’ll find many examples of tangible objects: lamps, phones, computers, and cars. Also, you can find intangible objects such as bank accounts and transactions.

Читайте также:  Python в управлении сетями

All of these objects share the two common key characteristics:

For example, a bank account has the state that consists of:

A bank account also has the following behaviors:

PHP objects are conceptually similar to real-world objects because they consist of state and behavior.

An object holds its state in variables that are often referred to as properties. An object also exposes its behavior via functions which are known as methods.

What is a class?

In the real world, you can find many same kinds of objects. For example, a bank has many bank accounts. All of them have account numbers and balances.

These bank accounts are created from the same blueprint. In object-oriented terms, we say that an individual bank account is an instance of a Bank Account class.

By definition, a class is the blueprint of objects. For example, from the Bank Account class, you can create many bank account objects.

The following illustrates the relationship between the BankAccount class and its objects. From the BankAccount class you can create many BankAccount objects. And each object has its own account number and balance.

Define a class

To define a class, you specify the class keyword followed by a name like this:

 class ClassName < //. >Code language: HTML, XML (xml)

For example, the following defines a new class called BankAccount :

 class BankAccount  Code language: HTML, XML (xml)

By convention, you should follow these rules when defining a class:

  • A class name should be in the upper camel case where each word is capitalized. For example, BankAccount , Customer , Transaction , and DebitNote .
  • If a class name is a noun, it should be in the singular noun.
  • Define each class in a separate PHP file.

From the BankAccount class, you can create a new bank account object by using the new keyword like this:

 class BankAccount  < >$account = new BankAccount();Code language: HTML, XML (xml)

In this syntax, the $account is a variable that references the object created by the BankAccount class. The parentheses that follow the BankAccount class name are optional. Therefore, you can create a new BankAccount object like this:

$account = new BankAccount;Code language: PHP (php)

The process of creating a new object is also called instantiation. In other words, you instantiate an object from a class. Or you create a new object from a class.

The BankAccount class is empty because it doesn’t have any state and behavior.

Add properties to a class

To add properties to the BankAccount class, you place variables inside it. For example:

 class BankAccount < public $accountNumber; public $balance; >Code language: HTML, XML (xml)

The BankAccount class has two properties $accountNumber and $balance . In front of each property, you see the public keyword.

The public keyword determines the visibility of a property. In this case, you can access the property from the outside of the class.

To access a property, you use the object operator ( -> ) like this:

 $object->property;Code language: HTML, XML (xml)

The following example shows how to set the values of the accountNumber and balance properties:

 class BankAccount < public $accountNumber; public $balance; > $account = new BankAccount(); $account->accountNumber = 1; $account->balance = 100;Code language: HTML, XML (xml)

Besides the public keyword, PHP also has private and protected keywords which you’ll learn in the access modifiers tutorial.

Add methods to a class

The following shows the syntax for defining a method in a class:

 class ClassName < public function methodName(parameter_list) < // implementation > >Code language: HTML, XML (xml)

Like a property, a method also has one of the three visibility modifiers: public , private , and protected . If you define a method without any visibility modifier, it defaults to public .

The following example defines the deposit() method for the BankAccount class:

 class BankAccount < public $accountNumber; public $balance; public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > > >Code language: HTML, XML (xml)

The deposit() method accepts an argument $amount . It checks if the $amount is greater than zero before adding it to the balance.

To call a method, you also use the object operator ( -> ) as follows:

$object->method(arguments)Code language: PHP (php)

The new syntax in the deposit() method is the $this variable. The $this variable is the current object of the BankAccount class.

For example, when you create a new object $account and call the deposit() method, the $this inside the method is the $account object:

$account = new BankAccount(); $account->accountNumber = 1; $account->balance = 100; $account->deposit(100);Code language: PHP (php)

Similarly, you can add the withdraw() method to the BankAccount class as follows:

 class BankAccount < public $accountNumber; public $balance; public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > > public function withdraw($amount) < if ($amount $this->balance) < $this->balance -= $amount; return true; > return false; > >Code language: HTML, XML (xml)

The withdraw() method checks the current balance.

If the balance is less than the withdrawal amount, the withdraw() method returns false .

Later, you’ll learn how to throw an exception instead. Otherwise, it deducts the withdrawal amount from the balance and returns true .

Summary

  • Objects have states and behaviors.
  • A class is a blueprint for creating objects.
  • Properties represent the object’s state, and methods represent the object’s behavior. Properties and methods have visibility.
  • Use the new keyword to create an object from a class.
  • The $this variable references the current object of the class.

Источник

Оцените статью