PHP Assigning a Default Function to a Class

Im relatively new to PHP, but realized that it is a powerful tool. So excuse my ignorance here.

I want to create a set of objects with default functions.

Therefore, instead of calling a function in a class, we can simply output the class / object variable and execute the default function using the toString () method.

Question: Is there a way to define a default function in a class?

Example

class String { public function __construct() { } //This I want to be the default function public function toString() { } } 

Using

 $str = new String(...); print($str); //executes toString() 
+4
source share
3 answers

There is no such function as the default function, but there are magic methods for classes that can be automatically activated under certain circumstances. In your case, you are looking for __toString()

http://php.net/manual/en/language.oop5.magic.php

Example from the manual:

 // Declare a simple class class TestClass { public $foo; public function __construct($foo) { $this->foo = $foo; } public function __toString() { return $this->foo; } } $class = new TestClass('Hello'); echo $class; ?> 
+10
source

Either put the toString function code inside __construct, or point to toString.

 class String { public function __construct( $str ) { return $this->toString( $str ); } //This I want to be the default function public function toString( $str ) { return (str)$str; } } print new String('test'); 
+1
source

__toString() is called when your object prints, i.e. echo $ str.

__call() is the default method for any class.

+1
source

Source: https://habr.com/ru/post/1393181/


All Articles