- This topic has 0 replies, 1 voice, and was last updated 1 year, 3 months ago by
jurgenmuca.
-
AuthorPosts
-
January 14, 2025 at 11:03 am #1390
jurgenmuca
ParticipantWarning: foreach() argument must be of type array|object, string given in C:\xampp\htdocs\OOPtutorial\index.php on line 56
Code:
public function sanitize($data){
foreach($data as $key =>$value){
$data[$key] = addslashes($value);
//adds slashes to the data and puts it to the same space to sanitize this data
}
$this->data = $data;
return $this;
}FIX: at the argument of the function sanitize, add array as typehinting so we can only expect arrays
public function sanitize(array $data){…
Fatal error: Uncaught TypeError: Signup::sanitize(): Argument #1 ($data) must be of type array, string given, called in C:\xampp\htdocs\OOPtutorial\index.php on line 90 and defined in C:\xampp\htdocs\OOPtutorial\index.php:54 Stack trace: #0 C:\xampp\htdocs\OOPtutorial\index.php(90): Signup->sanitize(”) #1 {main} thrown in C:\xampp\htdocs\OOPtutorial\index.php on line 54
Problem : at sanitize call the data passed must be an array
$data = ‘ ‘; //data
$myClass->sanitize($data)->create(‘my-data.json’)->save();
in this case sanitize($data) is getting a string
Fix:
$data = $_POST;
$myClass->sanitize($data)->create(‘my-data.json’)->save();
//now the function recieves an array as expected
//type hinting in arrays:
Fatal error: Uncaught TypeError: stuff(): Argument #1 ($data) must be of type car, string given, called in C:
function stuff(car $data){
var_dump($data);
}stuff(“something”);
in this case, function stuff expects an object of type car but receives a string
error: Uncaught TypeError: stuff(): Argument #1 ($data) must be of type car, bike given,
function stuff(car $data){
echo $data->range(20);
}$bike = new bike();
stuff($bike);
in this case the function expects a parameter of type car, but it was given a parameter of type bike
Fix:
in this case we can use an interface that can be extended by all classes and change the type to that interface
interface Vehicle{
public function range(float $miles);
}function stuff(vehicle $data){
echo $data->range(20) . “<br>”;
} -
AuthorPosts
- You must be logged in to reply to this topic.
