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 !

Recommended Answers

All 3 Replies

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.

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.

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;

?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.