0

Hi there,
Good day ! I have a question related to private variable in php class. I want to make check if someone accesses private variable, an exception is thrown says "this is private variable" and rest of the excecution of code didn't stop.

<?php 

class myClass
{

    public $str;
    private $pinCode = 111;

}


//object
$ob = new myClass();

$ob -> str = "This is a string.";

//code before the exception
echo $ob -> str;

    if(isset($ob -> pinCode))
    {
        throw new Exception("this is private variable");
    }

try
{
    echo $ob -> pinCode;
}

catch(Exception $e)
{
    echo 'Message : ' .$e -> getMessage();
}


//code after the exception
$name = "abc <br />";
echo $name;

?>

I know if we access private variable it will give an error but I want not to stop the execution of the code after the exception. Looking forward for reply, Thanks !

4
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by Bachu
0

Instead of accessing variable directely that will cause an error or exception. Write a generic method in class itself to serve the variable and value. This method can handle the exception itself. Otherwise you need to put conditions or try catch block in almost every line.

Edited by happygeek: fake sig deleted

0

I know if we access private variable it will give an error

This is a language restriction, you cannot override this behaviour. The workaround is to use the magic method __get. See the manual for more information.

-1

Try this

<?php 

class myClass
{

    public $str;
    private $pinCode = 111;

    function printPrivateVariable()
    {
        echo $this->pinCode;
    }

}


//object
$ob = new myClass();

$ob -> str = "This is a string.";

//code before the exception
echo $ob -> str.'<br />';

    if($ob -> printPrivateVariable())
    {
        throw new Exception("this is private variable");
    }

try
{
    echo $ob -> printPrivateVariable().'<br />';
}

catch(Exception $e)
{
    echo 'Message : ' .$e -> getMessage().'<br />';
}


//code after the exception
$name = "abc <br />";
echo $name;

?>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.