PHP boolean in class being a fatal error - php

I was working with php Booleans in a class when I noticed everytime I tried to make one I got an error here is a smaller version of my code
class my_class
{
public $hide_image == true;
}
thats the part of my code thats failing, without that boolean it works fine, but nothing on the page will show up when its there. How can I fix this? I am doing something wrong?

== compares the values of variables for equality. = sets.
public $hide_image = true;
http://php.net/manual/en/language.operators.comparison.php

The mistake that you using comparison operator "==" instead of "=". As a result your public property looks like that:
class my_class
{
public true;
}
Right:
class my_class
{
public $hide_image = true;
}

You are using double ==.
you should only use 1 = to assign a value

Try:
class my_class
{
public $hide_image = true;
}

Related

PHP Syntax not allowed

I would like to know why the syntax below cannot work with PHP. Anyone with an insight perhaps it does not make any sense or something.
($this->getState($state))->getEvent('eventOpen')->attach($observeCallback);
Basically the getState($state) method returns an object that within itself has both getEvent($eventName) and attach($observerCallbackToAttach).
However, this throws an error and doesn't work.
Am I breaking the rules for thinking this is a valid syntax?
Please note that ->attach($observeCallback) runs on the result of ->getEvent('eventOpen') -- not the result of $this->getState($state).
Check what the getEvent() method returns. For this to work it needs return $this;.
Or else, clarify you code as such:
$tmp = $this->getState($state);
$tmp->getEvent('eventOpen');
$tmp->attach($observeCallback);
Or alternatively, move the attach() method to the class used in the object returned by getEvent()
if the getState method returns an object which has 2 methods getEvent and attach then to make this work you have to return the same object with getEvent / attach. When you do getEvent()->attach() you are using the return value of getEvent not getState.
What you want to do to make this work is to return $this in your methods:
class Something
{
function setState($state)
{
if ($state != '') {
$this->state = $state;
}
return $this;
}
function setUberState($uberState)
{
if ($uberState != '') {
$this->uberState = $uberState;
}
return $this;
}
}
Using the above class you should be able to do:
$something = new Something();
$object = $something->setState('state')->setUberState('uberstate');

Unable to compare magic constant __METHOD__

Ok, I think I have something here...
Inside a class, im trying to condition a private function based on the used method's name.
So the code looks something like:
<?php
class my_class{
public function my_method($arg1) {
$this->private_function($arg1);
}
private function private_function($arg2){
if (__METHOD__ == "my_class::my_method"){
#THIS FAILS
}else{
#THIS WORKS
}
return;
}
}
(new my_class())->my_method($something);
If I do a var_dump() on __METHOD__ at the same level im trying to use it I'll get a nice string(19)"my_class::my_method". So I'm comparing a string to another one.
The following will also fail:
Cast both vars to string and compare them.
Copy __METHOD__ to a (string) $var and compare them.
Upper both strings and compare them.
Using single quotes for the text.
I might be wrong but I think I hit a bug here :(
PHP Version 5.6.1 - Win
__METHOD__ returns the current class method name. In your case this is my_class::private_function.
If you want to know the caller method, the cleanest way is to pass it as argument.
class my_class {
public function my_method($arg1) {
$this->private_function($arg1, __METHOD__);
}
private function private_function($arg2, $caller) {
if ($caller == "my_class::my_method") {
} else {
}
return;
}
}
You should try the __FUNCTION__
I guess __METHOD__ will return class name along with the function name.

define if statement for object [duplicate]

This question already has answers here:
how to create a php class which can be casted to boolean (be truthy or falsy)
(7 answers)
Closed 8 years ago.
Is there a way to define the boolean returned value for an if statement issued on my class instances?
I have a class implementing the array access interface and so on, but even if the wrapped array is empty:
if($class)
will always return true, since it is an object and does exists.
I'd rather not have to issue everytime an:
if(count($class))
Is there any way to achieve this?
If I get the point you can implement the countable interface; This requires you define the count() method, which let you know (by using it like count($myArrayAccessInstance)) if your internal array has items or not o whatever logic you want to define.
class MyAy implements ArrayAccess, Countable
{
private $data;
public function offsetExists($key)
{
# code...
}
public function offsetUnset($key)
{
# code...
}
public function offsetGet($key)
{
# code...
}
public function offsetSet($key, $value)
{
$this->data[$key] = $key;
}
public function count()
{
return $this->data > 0;
}
}
$my = new MyAy();
$my['user'] = "Ilpaijin";
if(count($my))
{
var_dump($my);
}
Given that you are implementing a class, maybe you could have a member which counts the elements in the array? Something like:
class MyClass {
public $numElems = 0;
private $elems = array();
...
public function add($elem) {
$elems[] = $elem;
$numElems++;
}
...
}
And then, do the iflike if($class->numElems) ...
Its not possible
In PHP an object when cast to bool always produces true. There is no way of changing that.
Check answers here
It's impossible to cast an object to a boolean related to a property inside the class because it always will return true. but I think you just need to create a function inside your class that allows you to return the boolean you need like this
public function bool()
{
return (count($this->array)>0);
}
when you need to use it, just call the function like this if ($obj->bool()) { ... } and another way to make your statements look like what you wanted to do in the begining is to define a class with a really short name, I usually use _, and this function should return the boolean you need just like this
function _ ($Obj)
{
return $Obj->bool();
}
finally, instead of testing on your class like this if ($class->bool()) which is a bit long, you do it like this
if (_($class))
{ /* do something fun */ }

Fatal error: Can't use method return value in write context in <filename> on line <ifconditioin statement>

I get the error for the following code
class Myclass {
//...variables
public function getName() {
return $this->strName;
}
public function checkDup() {
if(empty($this->getName())) { //HERE IS THE ERROR
$strMessage = 'Please Enter First Name';
return $strMessage;
}
}
}
$a = new Myclass (); //assume constructor is present and variables are set in class
$a->checkDup();
What could be the solution?
My getName() function returns the name of the variable
I figured out what was going wrong here.
I should be referring to the class member variable using $this and not call the getName() function again inside the class. This changes the function to :
public function checkDup() {
if(empty($this->strName)) { //HERE IS THE SOLUTION
$strMessage = 'Please Enter First Name';
return $strMessage;
}
}
change:
if(empty($this->getName())) {
to
$name = $this->getName();
if( empty($name) ) {
...
empty() only checks variables as anything else will result in a parse error
the empty construct is a bit silly that way. see the manual:
Note:
Prior to PHP 5.5, empty() only supports variables; anything else will
result in a parse error. In other words, the following will not work:
empty(trim($name)). Instead, use trim($name) == false.
I don't like any of the answers here. Yes you can reference $this->strName directly. But what if you can't? What if getName() has some important functionality?
Then the only option is to create another variable? $var = $this->getName();.
That also sucks.
Generically whenever I access a class property or function dynamically I enclose it in braces {} so:
I'll know it's dynamic.
I'll get meaningful errors if there are any.
Examples:
$this->{$variable};
$this->{$class->property};
$this->{$class->method()};
$this->{function()};
$this->{$array['index']};

Assigning a function's result to a variable within a PHP class? OOP Weirdness

I know you can assign a function's return value to a variable and use it, like this:
function standardModel()
{
return "Higgs Boson";
}
$nextBigThing = standardModel();
echo $nextBigThing;
So someone please tell me why the following doesn't work? Or is it just not implemented yet? Am I missing something?
class standardModel
{
private function nextBigThing()
{
return "Higgs Boson";
}
public $nextBigThing = $this->nextBigThing();
}
$standardModel = new standardModel;
echo $standardModel->nextBigThing; // get var, not the function directly
I know I could do this:
class standardModel
{
// Public instead of private
public function nextBigThing()
{
return "Higgs Boson";
}
}
$standardModel = new standardModel;
echo $standardModel->nextBigThing(); // Call to the function itself
But in my project's case, all of the information stored in the class are predefined public vars, except one of them, which needs to compute the value at runtime.
I want it consistent so I nor any other developer using this project has to remember that one value has to be function call rather then a var call.
But don't worry about my project, I'm mainly just wondering why the inconsistency within PHP's interpreter?
Obviously, the examples are made up to simplify things. Please don't question "why" I need to put said function in the class. I don't need a lesson on proper OOP and this is just a proof of concept. Thanks!
public $nextBigThing = $this->nextBigThing();
You can only initialize class members with constant values. I.e. you can't use functions or any sort of expression at this point. Furthermore, the class isn't even fully loaded at this point, so even if it was allowed you probably couldn't call its own functions on itself while it's still being constructed.
Do this:
class standardModel {
public $nextBigThing = null;
public function __construct() {
$this->nextBigThing = $this->nextBigThing();
}
private function nextBigThing() {
return "Higgs Boson";
}
}
You can't assign default values to properties like that unless that value is of a constant data type (such as string, int...etc). Anything that essentially processes code (such as a function, even $_SESSION values) can't be assigned as a default value to a property. What you can do though is assign the property whatever value you want inside of a constructor.
class test {
private $test_priv_prop;
public function __construct(){
$this->test_priv_prop = $this->test_method();
}
public function test_method(){
return "some value";
}
}
class standardModel
{
// Public instead of private
public function nextBigThing()
{
return "Higgs Boson";
}
}
$standardModel = new standardModel(); // corection
echo $standardModel->nextBigThing();

Categories