Jump to content

[SOLVED] "must be an instance of string, string given", wait what?


jordanwb

Recommended Posts

Error: Catchable fatal error: Argument 1 passed to playlist::add_song() must be an instance of string, string given, called in E:\xampp\htdocs\test\index.php on line 11 and defined in E:\xampp\htdocs\test\playlist.php on line 25

 

class playlist
{
private $songs;

function playlist ($songs = null)
{
	if ($songs != null)
	{
		if (is_array ($songs))
		{
			$this->songs = array ();
			foreach ($songs as $index => $song_path)
			{
				if (is_string ($song_path))
				{
					$this->songs[] = $song_path;
				}
			}
		}
	}
}

function add_song (string $path)
{

}
}

 

I'm making it so that you can only pass in a certain type, and you know not pass in garbage. It's seems that my string is not good enough for the parameter.

I didn't even know PHP supported type specific function params....  Then I tested some stuff, and I don't think it does.

 


function test(SomeClass $var) {
     echo $var->DoSomething();
}

class SomeClass {
     public function DoSomething() {

     }
}

$sc = new SomeClass();
test($sc);

 

When ever you "type $param," it interprets it as a class type, not a native type (string, int, so on).

 

Anyway, you'll have to make sure it's a string inside the function.

Edit:  Daniel obviously beat me too it, but oh well... posting it anyway ;p

 

 

Exactly.  (I never knew you could hint types at all lol x.x tested this just now)

 

When you put the array there, the input must be an array or it throws a catchable fatal error.

 

I expected if you passed it a single string it would convert it to an array with one element, but no, it doesn't.  I guess that's because it figures if you strictly want an array, it should strictly check it, not try to make things an array.

You can still do it with a string, fyi :)

 

Pretty sure this works

 

<?php

function lol (string $a) { echo $a; }

$mystr = (string) "hello, world!";

lol($mystr);

?>

 

Did you run the code?

Catchable fatal error: Argument 1 passed to lol() must be an instance of string, string given, called in C:\apache2\htdocs\test.php on line 7 and defined in C:\apache2\htdocs\test.php on line 3

 

You cannot type hint scalar values.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.