Why does my php base class expect an argument when I create it?

MyCLASS (123); ? >

this works, but returns this warning:

Warning: Missing argument 1 for myClass::myClass()

I read this and it seems that the constructor is expecting a value, so adding:

function myClass($input='')

the warning is removed, but does this seem unnecessary?

can someone tell me why it should determine the value to prevent this warning?

thanks for any pointers

+3
source share
5 answers

You use a method (functions in objects are called methods), which are the same name as the class. This is called a constructor; it has special meaning in OOP.

, , . , , new classname.

$test = new myClass(123);

. , . . , new myClass .

, . :

<?php
class myClass {
 var $input;
 var $output;

 function someOtherFunctionName($input) {
  $output = 'You entered: ' . $input;
  return $output;
 }
}

$test = new myClass;
echo $test->someOtherFunctionName(123);

?>

, , , PHP 5 __construct() , :

<?php
class myClass {
 var $input;
 var $output;

 function __construct($input) {
  $this->input = $input;  // This is a valid thing to do in a constructor
 }
}

PHP 5 manual.

+5

myClass , , ,

$test = new myClass(123);

class myClass {
 var $input;
 var $output;
 function myClass(){}
 function setInput($input) {
  $output = 'You entered: ' . $input;
  return $output;
 }
}

$test = new myClass;
echo $test->setInput(123);
+1

myClass, - . php4, php5.

, , , , .

:

$test = new myClass(123);

- , , .

+1

php considers your function "myClass" to be a constructor (because its name matches the name of the class) and calls it automatically after "new". If you do not want this, simply rename the function:

class MyClass {
   function foo($input) { ... }
...
}

$obj = new MyClass;
$obj->foo(bar);
0
source

If you want some parameters of methods / functions to be optional, you can specify their default values ​​in the declaration, as you did function myClass($input=NULL).

However, you are learning PHP4 and no longer supporting developers, look at PHP5.

0
source

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


All Articles