Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.