Jump to content

Custom magic methods?


Ivan Ivković

Recommended Posts

Is there any way to produce a custom magic method?

 

Let's say when I try to get an attribute that doesn't have any value, a method gets called that gives that attribute a value.

 

So I want a method to be triggered when I try to get a value from an attribute that doesn't have any value.

Link to comment
https://forums.phpfreaks.com/topic/255264-custom-magic-methods/
Share on other sites

Yes, something like that.

 

__set() is called when you try to set a value to a non-existing member.

__get() is called when you try to access a non-existing member.

 

I'm trying to find or 'create' a magic method that will respond when I try to access a member that does not have any value.

 

I don't want to overoccupy my constructor... So I want that function to be independent.

Is something like this what you need?

 

<?php
ini_set("display_errors", 1);
class a
{ private $p;

  function __get($name)
  { return $this->$name ?: "no value";
  }

  function __set($name, $value)
  { $this->$name = $value;
  }
}

$a = new a();
echo $a->p . "<br />";
$a->p = "123";
echo $a->p;
?>

 

dispalys:

 

no value

123

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.