Enforce property types?

In Java I was accustomed to declaring every variable and it’s type. I know PHP is weak typed and you don’t need to declare types, but is it possible? If memory serves in Java you’d do something like this.


class NewClass
{
	public int $myInt;//$myInt must be type int
	public MyOtherClass $other;//$other must be type MyOtherClass
}

Then any attempts to use the wrong type would throw an exception.

Now, you could make your properties private and apply a setter for every class property:

class NewClass
{
	private $myInt;
	private $other;
	
	public function setInt($int)
	{//can't use type hinting for ints, only objects
		
		if(!is_int($int))//note that this is strict and passing "1" will fail
		{
			throw new Exception("int required but ".gettype($int)." passed");
		}
	}
	
	public function setOther(MyOtherClass $other)
	{
		//this will throw Exception if it's incorrect type
		$this->other = $other;
		
	}
}

You could even do some stuff with magic functions if you were so inclined. But it all seems a bit messy. Am I missing something more simple and obvious?

PHP is a dynamically typed language, Java is a static typed language…so to answer your question. PHP is not Java so no.

PHP has argument hinting for arrays and objects, but not for native types (int, string, etc). It was proposed for PHP 5.4 but didn’t make it.
You can’t however force anything on properties.