Kom ihåg mig?
Home Menu

Menu


PHP getters i klasser, funkar det?

 
Ämnesverktyg Visningsalternativ
Oläst 2012-07-24, 19:57 #14
Conny Westh Conny Westh är inte uppkopplad
Klarade millennium-buggen
 
Reg.datum: Aug 2005
Inlägg: 5 166
Conny Westh Conny Westh är inte uppkopplad
Klarade millennium-buggen
 
Reg.datum: Aug 2005
Inlägg: 5 166
Jag har brutit ut den generella egenskapen att hantera getters och setetrs och lagt det i en abstract Rootklass så andra klasser kan ärva in beteendet och vissa egenskaper.

Så här blev det i min testkod:

Kod:
<?php
///////////////////////////////////////////////////////////////////////////////
// File: AbstractRoot.php
// Class: AbstractRoot
///////////////////////////////////////////////////////////////////////////////
abstract class AbstractRoot
{
    private $_ChildClassname;

	public function __construct($ChildClassname)
	{
		$this->ChildClassname = $ChildClassname;
	}

    public function __set($name, $value)
    {
        switch ($name)
        {
            case 'ChildClassname':
                $this->_ChildClassname = $value;
                break;

            default:
            		// By throwing Exception for undefined property we can enforce strict property definition rules
            		// we also achive better error messages for improved debugging during development
            		// this is necessare because of lack of support for strict properties in php 5.3.15
            		$error = "Error: __set property: " . $name . " not supported by class: " . $this->ChildClassname . "." ;
					throw new Exception($error);
					break;
        }
    }

    public function __get($name)
    {
        switch ($name)
        {
            case 'ChildClassname':
                return $this->_ChildClassname;
                break;

            default:
            		// By throwing Exception for undefined property we can enforce strict property definition rules
            		// we also achive better error messages for improved debugging during development
            		// this is necessare because of lack of support for strict properties in php 5.3.15
            		$error = "Error: __get property: " . $name . " not supported by class: " . $this->ChildClassname . ".";
					throw new Exception($error);
					break;
        }
        return null;
    }
}

?>
Kod:
<?php
///////////////////////////////////////////////////////////////////////////////
// File: Person.php
// Class: Person
///////////////////////////////////////////////////////////////////////////////
class Person extends AbstractRoot
{
    private $firstname;
    private $lastname;

	public function __construct($pFirstname, $pLastname)
	{
		parent::__construct(__CLASS__);

		// Always
		$this->firstname = $pFirstname;
		$this->lastname = $pLastname;
	}

	/* a String representation for every Person. */
	public function __toString()
	{
		return $this->firstname . " " . $this->lastname;
	}
}
?>
Kod:
<?php
///////////////////////////////////////////////////////////////////////////////
// File: PersonAge.php
// Class: PersonAge
///////////////////////////////////////////////////////////////////////////////
class PersonAge extends AbstractRoot
{
    private $firstname;
    private $lastname;
    private $age;

	public function __construct($pFirstname, $pLastname, $pAge)
	{
		parent::__construct(__CLASS__);

		// Always
		$this->firstname = $pFirstname;
		$this->lastname = $pLastname;
		$this->age = $pAge;
	}

	/* a String representation for every PersonAge. */
	public function __toString()
	{
		return $this->firstname . " " . $this->lastname . " (" . $this->age . ")";
	}
}
?>
Kod:
<?php
///////////////////////////////////////////////////////////////////////////////
// File: PropertiesTest.php
// Test for Class: AbstractRoot, Person, PersonAge
///////////////////////////////////////////////////////////////////////////////
class PropertiesTest
{
	public function __construct()
	{
		try
		{
			echo "\nTest of errormessage wehen faulty property ...\n";
			echo "\nStart testing class: Person.\n---------------------------------------\n\n";
			$rad = 0;

			echo "(row) - Firstname Lastname\n";
			# create a PHP Array and initialize it with Person objects
			$persons = array
			(
				new Person("Fredrik", "Framberg"),
				new Person("Greta", "Gavelstam"),
				new Person("Urban", "Urberg"),
				new Person("Anna", "Ambtesteg"),
				new Person("Henrik", "Hammarberg"),
				new Person("Kristina", "Karlestam"),
				new Person("Hans", "Hallin"),
				new Person("Berit", "Bygdén")
			);

			# print out the results - calls Person->__toString().
			foreach($persons as $person) echo "(" . ++$rad . ") - " . "$person\n";
		}
		catch (Exception $e)
		{
			echo 'Caught exception (1): ',  $e->getMessage(), "\n";
		}

		try
		{
			echo "\nTest of creating new object of class Person ...\n";
			$faultyPerson = new Person("Dennis","Harper");
			echo "This message will hopefully be written to console.\n";
		}
		catch (Exception $e)
		{
			echo 'Caught exception (2): ',  $e->getMessage(), "\n";
		}

		try
		{
			echo "\nTest of errormessage when faulty __set property ...\n";
			echo "(" . ++$rad . ") - " . "$faultyPerson\n";
			$faultyPerson->Age = 34;
			$faultyPerson->ShoeSize = 45;
			echo "Age: " . $faultyPerson->Age . " years.\n";
			echo "ShoeSize: " . $faultyPerson->ShoeSize . ".\n";

			echo "This message will not be written to console.\n";
		}
		catch (Exception $e)
		{
			echo 'Caught exception (3): ',  $e->getMessage(), "\n";
		}

		try
		{
			echo "\nTest of errormessage when faulty __get property ...\n";
			echo "(" . ++$rad . ") - " . "$faultyPerson\n";
			echo "ShoeSize: " . $faultyPerson->ShoeSize . ".\n";
			echo "Age: " . $faultyPerson->Age . " years.\n";

			echo "This message will not be written to console.\n";
		}
		catch (Exception $e)
		{
			echo 'Caught exception (4): ',  $e->getMessage(), "\n";
		}

		echo "\nDone testing class: Person.\n---------------------------------------\n\n";

		echo "\nStart testing class: PersonAge.\n---------------------------------------\n\n";
		try
		{
			echo "\nTest of errormessage when faulty __set property ...\n";
			$faultyPersonAge = new PersonAge("Arthur","Trent",47);
			echo "(" . ++$rad . ") - " . "$faultyPersonAge\n";
			$faultyPersonAge->age = 58;
			$faultyPersonAge->ShoeSize = 43;
			echo "ShoeSize: " . $faultyPersonAge->ShoeSize . ".\n";
			echo "Age: " . $faultyPersonAge->age . " years.\n";

			echo "This message will not be written to console.\n";
		}
		catch (Exception $e)
		{
			echo 'Caught exception (5): ',  $e->getMessage(), "\n";
		}

		try
		{
			echo "\nTest of errormessage when faulty __get property ...\n";
			//$faultyPersonAge = new PersonAge("Gary","Middleton",56);
			echo "(" . ++$rad . ") - " . "$faultyPersonAge\n";
			echo "Age: " . $faultyPersonAge->age . " years.\n";
			echo "ShoeSize: " . $faultyPersonAge->ShoeSize . ".\n";

			echo "This message will not be written to console.\n";
		}
		catch (Exception $e)
		{
			echo 'Caught exception (6): ',  $e->getMessage(), "\n";
		}

		echo "\nDone testing class: PersonAge.\n---------------------------------------\n\n";
	}
}

try
{
	$test = new PropertiesTest();
}
catch (Exception $e)
{
	echo 'Caught exception (7): ',  $e->getMessage(), "\n";
}

?>
Conny Westh är inte uppkopplad   Svara med citatSvara med citat
 


Aktiva användare som för närvarande tittar på det här ämnet: 1 (0 medlemmar och 1 gäster)
 

Regler för att posta
Du får inte posta nya ämnen
Du får inte posta svar
Du får inte posta bifogade filer
Du får inte redigera dina inlägg

BB-kod är
Smilies är
[IMG]-kod är
HTML-kod är av

Forumhopp


Alla tider är GMT +2. Klockan är nu 09:50.

Programvara från: vBulletin® Version 3.8.2
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
Svensk översättning av: Anders Pettersson
 
Copyright © 2017