Overriding Get Method

Hi all, I know this is the first of january but i’m trying to finish something.

It’s quite simple (or have to be ><) : I want to everride a getter method.

I’ve got an object with a field and I want to change the value befeore returning it

Apparently I just have to create the field in protected and create the getter method but it doesn’t work

It always send me an empty string…

Here is my code. I’ve put only $this->name but even with that it doesn’t work




protected $name;

public function getName() { 

	return $this->name;

}



What have I missed ?

Thanks

Dear Friend

The class in question should extend from CComponent or any other class extended from CComponent.




class TestModel extends CComponent

{

	

	protected $name="someName";

	

	public function getName()

        {

	  return $this->name;

        }

	public function setName($name)

        {

	  $this->name=$name;

        }

	

}

	

	$ob=new TestModel;

	echo $ob->name;


        $ob->name="someOtherName";

	echo $ob->name;



Regards.

Thanks for your answer.

My class extends the CActiveRecord class so I guess it’s ok, but it doesn’t work…

Check that the name field is not empty!

Do a


die($this->name)

and see if it prints what you expect it to. :)

The name field is not empty. If I use it like usual it’good… if I try to use get method, with private field, it’s empty.

It already was an existing field, in database…

Even if I return a string “test” , it’s still empty

Where do I have to put the “die” method, I don’t know what to expect of this ^^’

Dear Friend

Sorry I am not aware of that.

If you are using CActiveRecord, You are dealing with private or protected virtual properties,

then you have to override __set and __get methods.




class TestRecord extends CActiveRecord

{

	

	protected $name="someName"; //or private

	

	public function getName()

        {

	  return $this->name;

        }

	public function setName($name)

        {

	  $this->name=$name;

        }

	


        public function __get($name) 

        {

		$getter='get'.$name;

		if(property_exists($this,$name) && method_exists($this,$getter))

			return $this->$getter();

		else return parent::__get($name);

        }


	public function __set($name,$value) 

       { 

		$setter='set'.$name;

		if(property_exists($this,$name) && method_exists($this,$setter))

			return $this->$setter($value);

		else parent::__set($name,$value);

       }

}



Regards.

Yes ! that’s it.

I tought this was automatically done by Yii.

It works now I can go further. Thanks a lot