php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Return to Bug #52583
Patch example-cast-magic-method revision 2010-08-11 14:32 UTC by martin dot leucht at googlemail dot com

Patch example-cast-magic-method for Class/Object related Bug #52583

Patch version 2010-08-11 14:32 UTC

Return to Bug #52583 | Download this patch
Patch Revisions:

Developer: martin.leucht@googlemail.com

´╗┐class Time
{

	// UNIX timestamp (seconds since epoch)
	public $Timestamp;
	
	public function __construct($Timestamp)
	{
		$this->Timestamp = $Timestamp;
	}

	// example implementation for solution (1)
	public function __cast($Value)
	{
		if (is_string($Value))
		{
			$Timestamp = strtotime($Value);
			$this->Timestamp = $Timestamp;
		}
		elseif (is_number($Value))
		{
			$this->Timestamp = $Timestamp;
		}
		elseif ($Value instanceof Time2)
		{
			// Yep, Time2 is not implemented here. Use your fantasy, it's just an example.
			$this->Timestamp = $Value->getTimestamp();
		}
		else
		{
			// don't know how to cast
			return false;
		}
	}

	// example implementation for solution (2)
	public function __cast($Value)
	{
		if (is_string($Value))
		{
			$Timestamp = strtotime($Value);
			return new self($Timestamp);
		}
		elseif (is_number($Value))
		{
			return new self($Timestamp);
		}
		elseif ($Value instanceof Time2)
		{
			// Yep, Time2 is not implemented here. Use your fantasy, it's just an example.
			return new self($Value->getTimestamp());
		}
		elseif (is_array($Value))
		{
			// Well, I know this would be weird, but hey... we are so much dynamic!
			return count($Value);
		}
		// don't know how to cast
		throw new Exception("Don't know how to cast to class Time");
	}

}

// --- casting ---
// we have some data here, that could be of any type (hopefully compatible)
$Time = (Time)$SomeData;

// --- hinting ---
function getTimeString(Time $Time)
{
	return date('Y-m-d H:i:s', $Time->Timestamp);
}

echo getTimeString('today') . "\n";
echo getTimeString(123456789) . "\n";
echo getTimeString($Time) . "\n";
// ... and so on
 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Thu Oct 21 08:03:34 2021 UTC