PHP private accessor - php

I made a private variable in my class with a set and get functions but I keep on getting the following error:
Fatal error: Uncaught Error: Cannot access private property Car::$make
in C:\xampp\htdocs\PhpOOP\index.php:16 Stack trace: #0 {main} thrown
in C:\xampp\htdocs\PhpOOP\index.php on line 16
When I change it from private to public it works fine.
Here is my class:
<?php
class Car {
private $make;
public $model;
public $color;
public function starting(){
echo "Car Starting";
}
public function setMake($make){
$this->make = $make;
}
public function getMake(): string{
return $this->make;
}
}
And here is where I am creating an instance of the class and trying to use my methods.
<body>
<?php
include "classes/Car.php";
$car1->setMake("Honda");
echo $car1->getMake();
?>
</body>

You are not instantiating your class variable. You are including your class file, but you then need to instantiate the class
<body>
<?php
include "classes/Car.php";
$car1 = new Car();
$car1->setMake("Honda");
echo $car1->getMake();
?>
</body>

Fixed I was progressively learning objects in php. Was accessing the private variable when it was public. Then I turned it private to see how that worked. And my old code that was accessing it was causing the problem not the new stuff with the set and get methods.

Related

How to call the method of an anonymous class when the anonymous class is passed as a parameter to the class method of a normal class?

I'm using PHP 7.1.11
I've tried following code for an Anonymous Class which is declared as a parameter to a class method. I want to call the method present in an anonymous class. But I'm getting a fatal error. How should I call the anonymous class method successfully?
<?php
class Util {
private $logger;
public function __construct(){}
public function getLogger($logger) {
$this->logger = $logger;
}
public function setLogger($logger) {
$this->logger = $logger;
}
}
$util = new Util();
$util->setLogger(new class {
public function log($msg) {
echo $msg;
}
});
$util->setLogger()->log('Phil runs very fast'); // Ioutput should be : Phil runs very fast
?>
Output I'm currently getting :
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Util::setLogger(), 0 passed in anonymous_class_ex.php on line 27 and exactly 1 expected in anonymous_class_ex.php:13 Stack trace: #0 anonymous_class_ex.php(https://stackoverflow.com/posts/47605127/edit27): Util->setLogger() #1 {main} thrown in anonymous_class_ex.php on line 13
You'd run it like you would any dynamic reference to a callable, as a two-element array: [object, 'methodName']. Here the object is your anonymous class definition:
$util->setLogger([new class {
public function log($msg) {
echo $msg;
}
}, 'log']);
Here's a stand-alone runnable example for you to look at:
class Outer {
function runner(){
$this->runCallback([new class {
function anonymousClassMethod(){
echo "hi from anonymous class method";
}
}, 'anonymousClassMethod']);
}
function runCallback(callable $f){
$f();
}
}
$o = new Outer();
$o->runner();
I see 2 issues with your code.
You are not using the right method on $util
Instead of
$util->setLogger()->log('Phil runs very fast');
your code should be $util->getLogger()->log('Phil runs very fast');.
You want to getLogger since it was already set before.
Your implementation of getLogger() might be flawed
In my opinion, this method should not have any parameter and it should return something, which is actually missing in your code.
So instead of
public function getLogger($logger) {
$this->logger = $logger;
}
you should have something like
public function getLogger() {
return $this->logger;
}
With those 2 points addressed, your code works as expected. See here for yourself https://ideone.com/V2slho.

PHP private property should not be accessible in Child class

I have one silly doubts.
I'm setting username property as private in user class
But According to the rules private property should not be accessible
in Child class or inherited and outside of the class but it's happening
in my code. I just want to know where i did wrong.
<?php
class User{
private $username;
}
class UserRepository extends User{
public function get(){
return $this->username;
//this should give error can't access private property
}
public function set($username){
$this->username=$username;
//this should give error can't access private property
}
}
$UserReposetry =new UserRepository;
$UserReposetry->username='daulat';//this should give error.
echo $UserReposetry->username;//this should give error.
It should not work but it's working.
No way,
Here see the code and see result (error)
<?php
class User{
private $username="aaa";
}
class UserRepository extends User{
public function get(){
return $this->username;
}
}
$UserReposetry =new UserRepository;
echo $UserReposetry->get();//this should give error.
Output:
Notice: Undefined property: UserRepository::$username in C:\Users...........index.php on line 7
(To see this notice you have to set your error reporting as E_ALL)
And line 7 means return $this->username; , try using ::parent keyword too
In Your Code: You are just setting a new variable. So don't misunderstand that code is using private member.

What is the differece between private and protected in OOP?

I don't understand what is the different between private method and protected method in Object Oriented PHP. After make a method private , I'm able to access it from extends class. Please check the code below -
<?php
class person{
private function namedilam(){
return "likhlam";
}
public function kicu(){
return $this->namedilam();
}
}
class second extends person{
}
$info = new second;
echo $info->kicu();
The difference will become clear when you do it like this:
class Liam {
private getFirstName() {
return "Liam";
}
public function getName() {
return $this->getFirstName();
}
}
class Max extends Liam {
private function getFirstName() {
return "Max";
}
}
class Peter extends Liam {
public function getLiamsName() {
return $this->getFirstName();
}
}
$max = new Max();
echo $max->getName();
// returns "Liam", not "Max" as you might expect
$peter = new Peter();
echo $peter->getLiamsName();
// PHP Fatal error: Uncaught Error: Call to private method Liam::getFirstName() [...]
Max will return "Liam" because the getName() calls getFirstName() in the Liam class, not the one from the class extending it. This means with private methods you can make sure that whenever in your class you call this method exactly this one is used and it will never be overwritten.
To explain it in general terms:
private methods are only accessible inside the class. They can not be overwritten or accessed from outside or even classes extending it.
protected methods are accessible inside the class and in extending classes, but you can't call them from outside like:
$max = new Max();
$max->iAmProtected();
This will neither work with private or protected methods.

private class Error Undefined property

Good morning everybody, I have a two class, the first accesses the second class.
More on segunta class has a private $ my, and this gives the error Undefined property: session::$my in line, if($this->my)
I would be very grateful for the help.
Sample code,
class session{
public function run_session(){
..run..
data::run($line);
}
}
class data {
private $my = "../../my/";
public function run($line){
if($this->my.$line){
....run...
}
}
}
you must use like this
class data {
private $my = "../../my/";
public function run($line){
if($this->my.$line){ // here you are using $this, so the function must be called on object of class data
....run...
}
}
}
class session{
public function run_session(){
..run..
$data = new data(); // create object of class data, so that you can call the function run
$data->run($line);
}
}

From a usage standpoint, what's the difference between a private and protection class function?

I know the manual definition, but from a real life usage standpoint, what's the difference? When would you use one over the other?
EDIT:
use protected methods when you want a child class (one that extends your current (or parent) class) to be able to access methods or variables within the parent.
Here is the PHP Visibility Manual
private can be seen by no other classes except the one the variable/method is contained in.
protected can be seen by any class that is in the same package/namespace.
Code from the manual.
<?php
/**
* Define MyClass
*/
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// We can redeclare the public and protected method, but not private
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined
?>
When you know that a variable will be used only in that class and not in any other or extending class you would name it private. So if you extend the class and mistakenly name the variable as the name of a private this would give you error and thus prevent you from making mistakes.
If you for example use many pages in your web application and all of the pages are classes that extend one single class that handles header and footer of the page (cause it's always the same) you can override for example the default title of the page which is set up in parent class with protected variable setting.
I hope this helps.

Categories