This question already has answers here:
PHP Error : Fatal error: Constant expression contains invalid operations
(5 answers)
Closed 4 years ago.
I have the following code, where I get the error "PHP Fatal Error: Constant expression contains invalid operations". It works fine when I define the variable in the constructor. I am using Laravel framework.
<?php
namespace App;
class Amazon
{
protected $serviceURL = config('api.amazon.service_url');
public function __construct()
{
}
}
I have seen this question: PHP Error : Fatal error: Constant expression contains invalid operations
But my code does not declare anything as static, so that did not answer my question.
As described here
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
The only way you can make this work is :-
<?php
namespace App;
class Amazon
{
protected $serviceURL;
public function __construct()
{
$this->serviceURL = config('api.amazon.service_url');
}
}
Initializing class properties is not allowed this way. You must move the initialization into the constructor.
Another working alternative I used is with boot( ) with Laravel Eloquent:
<?php
namespace App;
class Amazon {
protected $serviceURL;
protected static function boot()
{
parent::boot();
static::creating(function ($model){
$model->serviceURL = config('api.amazon.service_url');
});
} }
Related
I'm attempting to create a custom plugin block in Drupal. When attempting to actually access the services that I've registered I continue to get the following exception:
NOTICE: PHP message: Error: Class 'Drupal\MyNamespace\MyRegisteredService' not found in /var/www/html/web/core/lib/Drupal/Component/DependencyInjection/Container.php on line 259 #0 /var/www/html/web/core/lib/Drupal/Component/DependencyInjection/Container.php(173): Drupal\Component\DependencyInjection\Container->createService(Array, 'foo....')
I have registered the services correctly, and have set up dependency injection correctly (I believe) it's just accessing the services that is not working.
My file structure currently looks like:
- web
- modules
- custom
- foo
- foo.services.yml
- src
- MyService.php
- Plugin
- Block
- FooBlock.php
foo.services.yml looks like:
services:
foo.my_service:
class: Drupal\MyNamespace\MyRegisteredService
autowire: true
FooBlock.php looks like (simply for dependency injection):
namespace Drupal\foo\Plugin\Block;
use Drupal\MyNamespace\MyRegisteredService
use Drupal\Console\Bootstrap\Drupal;
use Drupal\Core\Block\BlockBase;
use GuzzleHttp\Client;
use Http\Client\Exception;
use phpDocumentor\Reflection\Types\Array_;
use stdClass;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FooBlock extends BlockBase implements ContainerFactoryPluginInterface {
private $my_service;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('foo.my_service'),
);
}
function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
Drupal\MyNamespace\MyRegisteredService $my_registered_service,
) {
$this->my_registered_service = $my_registered_service;
}
MyService.php looks like:
<?php
namespace Drupal\MyNamespace;
class MyService
{
static function say_hello()
{
return 'hello world';
}
}
I'm not sure if the way that I'm trying to set this up is incorrect or if I haven't set up dependency injection correctly. Some things that I have tried with no success is changing the namespace and removing Drupal\ from it but this changed little.
I've also tried following several guides (such as this) on how set up services, with little luck.
Any help would be appreciated.
I am not sure about the actual name of your service or namespace path, but I can see a few inconsistencies in your placeholder references:
Please change all references of Drupal\MyNamespace\MyRegisteredService to Drupal\foo\MyRegisteredService where foo is the name of your module. This should be lower cased.
Secondly Drupal\MyNamespace\MyRegisteredService references a class name MyRegisteredService whereas the example class name you give is MyService. These should be equal, so either go with one or the other.
This question already has an answer here:
Smart cast (automatic type promotion) using 'is' is not working
(1 answer)
Closed 2 years ago.
I am working with dart without allowing implicit dynamics and casts and I noticed the following:
When working with a local variable, I can use a type check on that variable and if the test passes, the compiler will just assume that I can use that variable as that type:
var emp; // set to something
if (emp is Person) {
// The compiler infers that emp is a person within this scope
// so it allows me to use Person's member functions and variables
// without the need for explicit typecast
// https://dart.dev/guides/language/language-tour#type-test-operators
emp.firstName = 'Bob';
}
However, this does not work if the variable is the member variable of an object:
class SuperPerson {
Object _emp;
/* Various things that could be doing things with _emp here */
void memberFun() {
if (_emp is Person) {
_emp.firstName = 'Bob'; // ERROR: The setter firstName is not defined for type Object.
(_emp as Person).firstName = 'Bob'; // workaround but would like to avoid casts that could fail.
}
}
}
Why is that and how can I overcome it?
Could it be because of potentially other threads changing the value of _emp in between the test and the use?
Edit: I had forgotten that I had already answered this question. See that one instead.
(Since this answer had already been accepted at the time of this edit, I cannot delete it.)
Should I get the following error:
class.dart:11:11: Error: The getter '_privateID' isn't defined for the class 'Y'.
- 'Y' is from 'class.dart'.
Try correcting the name to the name of an existing getter, or defining a getter or field named '_privateID'.
From the following code?
mixin.dart:
class Mixin {
static int _nextID = 0;
int publicID = _nextID++; // I only need one of these lines
int _privateID = _nextID++; // but this variable is inaccessible
}
class.dart:
import 'mixin.dart';
class X with Mixin {
void run() {
print(publicID); // no error here
}
}
class Y with Mixin {
void run() {
print(_privateID); // Error: _privateID not defined
}
}
void main() {
Y().run();
}
Or is this a bug? If it's not a bug, I'd like to understand why this behavior is reasonable.
When I instead define the mixin in the same file as the above classes, I get no error.
(Dart SDK 2.4.1.)
It is not a bug.
The private field is inherited, but you cannot access it because its name is private to a different library.
Dart's notion of "privacy" is library private names.
The name _privateID in the mixin.dart library introduces a library private name. This name is special in that it can only be written inside the same library.
If someone writes _privateID in a different library, it is a different name, one unique to that library instead.
It is as if private names includes the library URI of the library it is written in, so what you really declare is a name _privateID#mixin.dart.
When you try to read that field in class.dart, you write ._privateID, but because it is in a different library, what you really write is ._privateID#class.dart, a completely different name, and the classs does not have any declarations with that name.
So, if one class needs to access a private member of another class (or mixin, or anything), then the two needs to be declared in the same library, because otherwise they cannot even write the name of that variable.
That is why the code works if you write the mixin in the same library.
If you want to move the mixin to a separate file, but not necessarily a separate library, you can use a part file.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Today, I reviewed same Android code, and found a strange phenomenon.
It is the anonymous internal class directly called the external class instance method.
In my mind, directly calling a method is equivalent to adding this directly before the method, and this is an instance of an inner class.
According to this logic, an instance of an external class is invoked directly in the anonymous inner class, that will caused the compile ERROR.
But actually compile this application, and no problem. And the running log is normal.
Therefore, writing a simple Demo to verify the previous concept is wrong. code show as below:
public class InnerClass {
public static void main(String[] args) {
new InnerClass().process();
}
public void process() {
new Thread() {
#Override
public void run() {
System.out.println(toString("test"));
}
}.start();
}
public String toString(String string) {
return string;
}
}
In the Oracle:
In the OpenJDK:
So, What is the difference of the anonymous internal class directly call the external class instance method in the OpenJDK and Oracle?
Where can I find documentation to see these differences?
I worked hard, but did not get a clear answer.
Thanks.
P.S.
In According to my point of view
public class InnerClass {
public static void main(String[] args) {
new InnerClass().process();
}
public void process() {
new Thread() {
#Override
public void run() {
// In According to my point of view
// toString("test")
// <==>
// this.toString("test")
// and `this` is the instance of Thread
// what's the error of my view?
System.out.println(toString("test"));
}
}.start();
}
public String toString(String string) {
return string;
}
}
The problem is that
public void run() {
System.out.println(toString("test"));
}
is calling toString on the anonymous Thread subclass, and that is Thread::toString(). There is no Thread::toString(String), and the toString(String) method from the enclosing scope is not considered.
The JLS states that it will only check an enclosing / outer class for a method if there is no method with the required name in the inner class. See JLS 15.12.1:
If the form is MethodName, that is, just an Identifier, then:
If the Identifier appears in the scope of a visible method declaration
with that name (§6.3, §6.4.1), then:
If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or
interface to search is T.
This search policy is called the "comb rule". It effectively looks for methods in a nested class's superclass hierarchy before looking
for methods in an enclosing class and its superclass hierarchy. See
§6.5.7.1 for an example.
As to why OpenJDK Java 7 accepts your test class .... if that is actually true, I'd call that a compiler bug. But it would be a general Java 7 bug not an OpenJDK specific one. The javac codebases are (AFAIK) identical for Oracle and OpenJDK releases of the same version.
Interestingly, I have a copy of Oracle Java 6, and javac from that version also calls this a compilation error as well.
$ /usr/java/jdk1.6.0_45/bin/javac InnerClass.java
InnerClass.java:10: cannot find symbol
symbol: method toString(java.lang.String)
System.out.println(toString("test"));
^
1 error
So ... maybe ... you should rerun your OpenJDK Java 7 test, and make sure you are compiling the same source code!
This question already has answers here:
Why can't class fields be var? [duplicate]
(4 answers)
Closed 6 years ago.
Hey I'm trying to Define a mock database . I'm encountering an error while trying to equate var to Mock<'Repository'> The error is :
The contextual keyword 'var' may only appear within a local variable declaration Or In Script Code.
The Code that I have written is :
public class MockingDatabse
{
//Mock a Payment Info
var newPayment = new Mock<IPayment>();
}
I know that I can replace 'var' with 'Mock<"Repository">'. But I wanna know I'm not able to use
'var'
Try this:
public class MockingDatabse
{
//Mock a Payment Info
Mock<IPayment> newPayment = new Mock<IPayment>();
}