Jump to content

type casting


mkooij

Recommended Posts

Dear fellow programmers,

I've got a problem with type casting in php.

I've got the the following code ( it's a test so it doesn't do very mutch)

 

<?php
class test{
  function  Casted(string $mysting,int $myint){
  
         echo 'your string is '. $mysting;
         echo 'your integer is '.$myint;


}

}

$myfunction = new test;

$myfunction.Casted('hello world',1234567);


?>

 

The above code generates an error on the line where I try to call the function by saying that the 1st variable does not have the right type... :S

 

does anyone know how ( or if it possible at all) to do the above?

 

Thanks and happy coding!

Link to comment
https://forums.phpfreaks.com/topic/41754-type-casting/
Share on other sites

I've got PHP Version 5.1.2

 

 

when I run the code below

<?php

ini_set('error_reporting', E_ALL);

class CTest{

 function  Casted(string $mysting,int $myint){
  
         echo 'your string is '. $mysting;
         echo 'your integer is '.$myint;


}

}

$test = new CTest;
$test->Casted("test",12345);


?> 

 

I get the following fatal error:

 

Fatal error: Argument 1 passed to CTest::Casted() must be an object of class string, called in /var/www/gaatloos/gda_test/cast.php on line 19 and defined in /var/www/gaatloos/gda_test/cast.php on line 6

Link to comment
https://forums.phpfreaks.com/topic/41754-type-casting/#findComment-202475
Share on other sites

What you are talking about here is type hinting not type casting. Unless you hvae create the objects string and int your code will error because they are not native php objects.

 

A small example...

 

<?php
  
  class a {
    public function test() {
      echo "foo";
    }
  }

  class b {
    public function test(a $a) {
      $a->test();
    }
  }

  $a = new a();
  $b = new b();
  $b->test();

?>

Link to comment
https://forums.phpfreaks.com/topic/41754-type-casting/#findComment-202543
Share on other sites

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.