假设我有一个这样的对象:
$user = (object) [
'username' => 'foo',
'post' => (object) [
'title' => 'bar'
],
];
现在我想获取用户帖子标题的值,但我想确保user
,posts
和title
都不为null或未定义。现在我正在检查如下:
if(isset($user) && $user->post && $user->post->title)
有更优雅的方式吗?
我不确定我是否在标题中描述得很好。如果您知道更好的措辞,请更正。
答案 0 :(得分:1)
isset()
接受多个参数,除非全部设置(而不是false
),否则将返回null
,因此您可以执行此操作:
isset($user, $user->post, $user->post->title)
答案 1 :(得分:1)
检查一切都是多余的。您需要检查的是最低级别的属性if (isset($user->post->title)) {
// do something
}
:
#*****************************************************************
# Neo4j configuration
#*****************************************************************
# The name of the database to mount
#dbms.active_database=graph.db
# Paths of directories in the installation.
#dbms.directories.data=data
#dbms.directories.plugins=plugins
#dbms.directories.certificates=certificates
# This setting constrains all `LOAD CSV` import files to be under the `import` directory. Remove or uncomment it to
# allow files to be loaded from anywhere in filesystem; this introduces possible security problems. See the `LOAD CSV`
# section of the manual for details.
dbms.directories.import=import
# Whether requests to Neo4j are authenticated.
# To disable authentication, uncomment this line
dbms.security.auth_enabled=false
#*****************************************************************
# Network connector configuration
#*****************************************************************
# Bolt connector
dbms.connector.bolt.type=BOLT
dbms.connector.bolt.enabled=true
dbms.connector.bolt.tls_level=OPTIONAL
# To have Bolt accept non-local connections, uncomment this line
dbms.connector.bolt.address=0.0.0.0:7687
# HTTP Connector
dbms.connector.http.type=HTTP
dbms.connector.http.enabled=true
# To accept non-local HTTP connections, uncomment this line
dbms.connector.http.address=0.0.0.0:7474
# HTTPS Connector
dbms.connector.https.type=HTTP
dbms.connector.https.enabled=true
dbms.connector.https.encryption=TLS
# To accept non-local HTTPS connection, change 'localhost' to '0.0.0.0'
dbms.connector.https.address=0.0.0.0:7473
# Number of Neo4j worker threads.
#dbms.threads.worker_count=
答案 2 :(得分:0)
自php 7.0起,使用空合并运算符(??
)即可轻松实现。
如果存在并且不为NULL,则返回其第一个操作数;否则返回第二个操作数。
因此,要获取字段的值,同时检查是否已设置所有变量和字段,您只需执行以下操作:
$title = $user->post->title ?? null