SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist hessodreamy's Avatar
    Join Date
    Apr 2005
    Location
    uk
    Posts
    518
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)

    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.
    Code:
    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:
    Code:
    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?

  2. #2
    ¬.¬ shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    PHP is a dynamically typed language, Java is a static typed language...so to answer your question. PHP is not Java so no.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  3. #3
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    8,897
    Mentioned
    138 Post(s)
    Tagged
    2 Thread(s)
    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.
    Rémon - Hosting Advisor

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •