Let's say I have got the following class:
class Test
{
function __construct()
{
// initialize some variable
$this->run();
}
function run()
{
// do some stuff
$this->handle();
}
function handle()
{
}
}
Normally I would create an instance like:
$test = new Test();
However I don't really need the $test
anywhere since the functions in the class do all the work once and after that I won't need the instance of the class anymore.
What should I do in this situation or should I just do: $test = new Test();
I hope it makes sense what I'm trying to say if not please tell me.
Syntax: We define our own class by starting with the keyword 'class' followed by the name you want to give your new class. <? php class person { } ?> Note: We enclose a class using curly braces ( { } ) … just like you do with functions.
PHP: Class Constants When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).
Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes.
$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object.
They should probably be static functions, if they don't require an instantiated instance:
class Test
{
private static $var1;
private static $var2;
// Constructor is not used to call `run()`,
// though you may need it for other purposes if this class
// has non-static methods and properties.
// If all properties are used and discarded, they can be
// created with an init() function
private static function init() {
self::$var1 = 'val1';
self::$var2 = 'val2';
}
// And destroyed with a destroy() function
// Make sure run() is a public method
public static function run()
{
// Initialize
self::init();
// access properties
echo self::$var1;
// handle() is called statically
self::handle();
// If all done, eliminate the variables
self::$var1 = NULL;
self::$var2 = NULL;
}
// handle() may be a private method.
private static function handle()
{
}
}
// called without a constructor:
Test::run();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With